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 = num[0];
for(int i=0; i<num.size(); i++)
{
if(count == 0)
{
count = 1;
number = num[i];
}
else
{
if(num[i] == number)
count++;
else
{
count--;
if(count==0)
{
number = num[i];
}
}
}
}
return number;
}
};