key: map
Runtime: 44 ms/ beats 9.23%
Reference: blog
public:
int majorityElement(vector<int>& nums) {
map<int,int> mapcnt;
map<int,int>::iterator iter;
for(int i = 0; i < nums.size(); i++)
{
if((iter=mapcnt.find(nums[i]))==mapcnt.end())
mapcnt.insert(pair<int,int>(nums[i],1));
else
mapcnt[nums[i]]++;
if(mapcnt[nums[i]] > nums.size()/2)
return nums[i];
}
return 0;
}
};
Update: Moore
Runtime: 16 ms / beats 72.25%
Reference:discuss
class Solution {
public:
int majorityElement(vector<int>& nums) {
int res = nums[0];
int cnt = 1;
for(int i = 1; i< nums.size(); i++)
{
if(res != nums[i])
cnt--;
else
cnt++;
if(cnt == 0)
{
res = nums[i];
cnt = 1;
}
}
return res;
}
};