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.
分析:
本题让我们寻找超过出现n/2的数,可以采用多数投票算法,具体代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int num = nums.size();
int major, count = 0;
for(int i = 0; i < num; ++i)
{
if(count == 0) major = nums[i];
if(nums[i] == major)
count++;
else
count--;
if(count > num/2) return major;
}
return major;
}
};