给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3]
输出:3
示例 2:
输入:nums = [2,2,1,1,1,2,2]
输出:2
提示:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
摩尔投票:⭐最优解
class Solution { public: int majorityElement(vector<int>& nums) { int m = 114514; // 初始化比较值为114214(可以是任意整数) int count = 0; //计数器 for (auto && num : nums) { // 遍历 if (num == m) { // 相等就++ count++; } else { // 不等就-- count--; } if (count <= 0) { // 如果计数器<=0,说明相同的个数和不同的个数已经抵消,只要数组中存在过半值,那么不用担心找不到,同类与不同类相消最后一定剩下一个有最多同类的值。 m = num;// 数组前方全被抵消,换下一个重新开始找同类 count = 1; // 以他开始,所以至少有一个同类 } } return m; } };
哈希表法:
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> counts; int majority = 0, cnt = 0; for (int num: nums) { ++counts[num]; if (counts[num] > cnt) { majority = num; cnt = counts[num]; } } return majority; } };
随机化法:
class Solution { private int randRange(Random rand, int min, int max) { return rand.nextInt(max - min) + min; } private int countOccurences(int[] nums, int num) { int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == num) { count++; } } return count; } public int majorityElement(int[] nums) { Random rand = new Random(); int majorityCount = nums.length / 2; while (true) { int candidate = nums[randRange(rand, 0, nums.length)]; if (countOccurences(nums, candidate) > majorityCount) { return candidate; } } } }
排序法:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };
分治法:
class Solution { int count_in_range(vector<int>& nums, int target, int lo, int hi) { int count = 0; for (int i = lo; i <= hi; ++i) if (nums[i] == target) ++count; return count; } int majority_element_rec(vector<int>& nums, int lo, int hi) { if (lo == hi) return nums[lo]; int mid = (lo + hi) / 2; int left_majority = majority_element_rec(nums, lo, mid); int right_majority = majority_element_rec(nums, mid + 1, hi); if (count_in_range(nums, left_majority, lo, hi) > (hi - lo + 1) / 2) return left_majority; if (count_in_range(nums, right_majority, lo, hi) > (hi - lo + 1) / 2) return right_majority; return -1; } public: int majorityElement(vector<int>& nums) { return majority_element_rec(nums, 0, nums.size() - 1); } };
标签:count,相消,return,枚举法,nums,int,lo,随机化,majority From: https://www.cnblogs.com/slowlydance2me/p/16893923.html