Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
在一个数组中,出现次数大于n/2次数的只可能有一个。开始时count为0,如果数组中的数和candidate相同,则加1。如果不同,则减1。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = 0;
int count = 0;
for(int i = 0; i < nums.size(); i ++)
{
if(count == 0)
{
candidate = nums[i];
count = 1;
}
else
{
if(nums[i] == candidate)
count ++;
else
count --;
}
}
return candidate;
}
};