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.
摩尔投票法:http://mabusyao.iteye.com/blog/2223195
这种投票法先将第一个数字假设为众数,然后把计数器设为1,比较下一个数和此数是否相等,若相等则计数器加一,反之减一。然后看此时计数器的值,若为零,则将当前值设为候选众数。以此类推直到遍历完整个数组,当前候选众数即为该数组的众数。代码如下
class Solution {
public:
int majorityElement(vector<int>& nums) {
int nowNum = nums[0];
int count = 1;
for(int i = 1; i < nums.size() ; i ++){
if(count == 0){
nowNum = nums[i];
count = 1;
}else{
if(nums[i] == nowNum){
count ++;
}else{
count --;
}
}
}
return nowNum;
}
};