给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
思路:
摩尔投票算法:
相同进入,不同抵消,因为众数大于n/2,所以谁也抵消不过他
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 int count = 0; 5 int m =0 ; 6 for(int i = 0;i<nums.size();i++) 7 { 8 if(count == 0) 9 { 10 m = nums[i]; 11 count++; 12 } 13 else if(m == nums[i]) 14 count++; 15 else 16 count--; 17 } 18 return m; 19 } 20 };