169. Majority Element
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.
找出数列中个数超过一半的数,假定数列不为空且该数一定存在。
代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
int index = ;
int candidate = nums[];
for(int i = ; i < n; i++)
{
if(candidate == nums[i])
{
index ++;
}
else
{
index --;
}
if(index < )
{
candidate = nums[i];
index = ;
}
}
return candidate;
}
};