Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
比较普通的方法是用哈希表,后来通过grandyang的博客https://www.cnblogs.com/grandyang/p/4233501.html,了解到还有一种方法叫摩尔投票法 Moore Voting,需要 O(n) 的时间和 O(1) 的空间。该方法有个前提条件是一定有一个过半数的数存在。然后,具体做法是:首先假设第一个数是要求的过半数的值,并设置一个计数器值为1.接下来遍历数组,如果不等于假设的值,则计数器减1,否则,计数器加1.当计数器的值减为0,重新设置过半数的值为新的值。
该想法很巧妙,主要思想是如果计数器为0了,意味着这个数在前面一段的数中个数等于一半,不符合要求。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 1, res = nums[0];
for(int i=1; i<nums.size(); ++i){
if(cnt == 0) res = nums[i];
if(nums[i] == res) cnt++;
else cnt--;
}
return res;
}
};