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;
}
思路比較簡單:只要按順序找數列,兩個兩個地取出來,只要是不一樣的數,就對消掉。如果相同,就保留下來並記錄個數,最後剩下的就是主元素。