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.
int majorityElement(vector<int>& nums) {
int majorNum = nums.at(0);
int countOfMN = 1;
for (int i = 1; i < nums.size(); ++i)
{
if (!countOfMN)
{
majorNum = nums.at(i);
countOfMN = 1;
}
else if (majorNum == nums.at(i))
{
++countOfMN;
}
else --countOfMN;//majorNum != nums.at(i)
}
return majorNum;
}
思路比较简单:只要按顺序找数列,两个两个地取出来,只要是不一样的数,就对消掉。如果相同,就保留下来并记录个数,最后剩下的就是主元素。