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 count = 0;
int number;
vector<int>::iterator iter = num.begin();
for(number = *iter; iter != num.end(); ++iter)
{
if(number == *iter)
++count;
else if(--count < 0)
{
number = *iter;
count = 1;
}
}
return number;
}
};
Notes:
有的面试题会要求时间复杂度为O(n),空间复杂度为O(1).
这道题主要突破点在要找的数出现次数超过了⌊ n/2 ⌋次,也就是说它的出现次数比总数的一半还要多。那么我们可以这样想:如果设这个数为x,则 x的个数 - 其他所有数的个数 > 0.
这样就可以想到一次遍历就能找到这个数了。