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.
- 求众数(也就是数组出现次数超过一半的那个数),最优的时间复杂度是O(n).
C++ Code:
class Solution {
public:
int majorityElement(vector<int> &num) {
int majorityNum = 0;
int count = 0;
for (int i = 0; i < num.size(); i++)
{
if (count == 0)
{
majorityNum = num[i];
count = 1;
}
else
{
if (majorityNum == num[i])
{
count++;
}
else
{
count--;
}
}
}
return majorityNum;
}
};