哈希:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int len=nums.size();
unordered_map<int,int> map;
for (int i=0;i<len;i++)
{
if(map.find(nums[i])==map.end())
{
map[nums[i]]=1;
}
else
{
map[nums[i]]++;
}
}
int seq=len/2;
int ans=nums[0];
for(auto pair:map)
{
if(pair.second>seq)
{
ans=pair.first;
}
}
return ans;
}
};
随机:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int len=nums.size();
while(true)
{
int index=rand()%len;
int res=nums[index];
int count=0;
for(auto num:nums)
{
if(num==res)
{
++count;
}
}
if(count>len/2)
{
return nums[index];
}
}
return -1;
}
};
类似分治:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int can=-1;
int count=0;
for(int num:nums)
{
if(count>0)
{
if(num!=can)
count--;
else
count++;
}
else{
can=num;
count++;
}
}
return can;
}
};