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> &num) {
int nID=num[0];
int nCount=0;
vector<int>::iterator iter=num.begin();
for(; iter!=num.end();++iter)
{
if(*iter==nID)
{
++nCount;
}
else
{
--nCount;
}
if(nCount==0)
{
nID=*iter;
nCount=1;
}
}
return nID;
}
};