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>& nums) {
/*
unordered_map<int ,int>bk;
for (int i=0;i<nums.size();i++)
{
bk[nums[i]]++;
if(bk[nums[i]]>nums.size()/2)
{
return nums[i];
}
}
*/
int me=0;
int count=0;
for(int i=0;i<nums.size();i++)
{
if(count==0)
{
me=nums[i];
count=1;
}
else
{
if(nums[i]==me)
{
count++;
}
else
{
count--;
}
}
}
return me;
}
};