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
解法:因为这个主要元素大于一半,所以,可以使用一个count,先取第一个作为结果,如果下一个元素跟这个相等,那么就count+1,否则就减一。如果=0,就重新取下一个数作为结果。有点像对对消。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ret = nums[0], count=1;
for(int i = 1; i < nums.size();++i)
{
if(count == 0)
{
count++;
ret = nums[i];
continue;
}
if(nums[i] != ret)
count--;
else
count++;
printf("%d ", count);
}
return ret;
}
};