class Solution
{
public:
int majorityElement(vector<int>& nums)
{
int length=nums.size();
if(length==1)
{
return nums[0];
}
map <int,int> m;
int temp;
for(int i=0;i<length;i++)
{
temp=nums[i];
auto iter=m.find(temp);
if(iter!=m.end())
{
iter->second=iter->second+1;
if(iter->second>length/2)
{
return iter->first;
}
}
else
{
m.insert(make_pair(temp,1));
}
}
return -1;
}
};
Leetcode——169. 多数元素
最新推荐文章于 2023-11-04 16:47:35 发布