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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
超过一半的数,开始记为0位置上的数,以后每遇到一个相同的,则计数+1;若不相同则计数-1;计数为0 则取当前的。因为major超过一半,因此会抵消掉其他数,最后剩下的就是major.
代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major=nums[0];
int c=1;
for(int i=1;i<nums.size();++i)
{
if(c==0)
{major=nums[i];c=1;}
else if(major==nums[i])
c++;
else
c--;
}
return major;
}
};