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
分析:
假设众数存在并且数组不为空,求数组中元素的众数。采用摩尔投票计数法:假设当前数为众数,若后面的值与之相等则计数加一,否则减一,计数值为0,则换下一个数为众数,依次遍历完,则当前所选数为众数。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int res = nums[0];
int count = 1;
for(int i=1; i<nums.size(); i++)
{
if(nums[i] == res)
count++;
else
count--;
if(!count)
{
res = nums[i];
count = 1;
}
}
return res;
}
};