题目:
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 size = nums.size();
int res = 0;
int cnt = 0;
for(int i = 0;i < size;++i)
{
if(cnt == 0)
{
res = nums[i];
cnt++;
}
else
{
if(res == nums[i])
cnt++;
else
cnt--;
}
}
return res;
}
};