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.
if extend the problem to more than⌊ n/k ⌋ times, need a k-1 size array.
class Solution {
public:
int majorityElement(vector<int> &num)
{
if (num.empty())
return 0;
int repeat = 1;
int cur = num[0];
for (int i = 1; i < num.size(); i++)
{
if (cur == num[i])
repeat++;
else if (--repeat == 0)
{
cur = num[i];
repeat = 1;
}
}
return cur;
}
};