https://leetcode.com/problems/majority-element/description/
Solution 1. Use Boyer–Moore majority vote algorithm.
http://shxi.blogspot.com/2017/11/boyermoore-majority-vote-algorithm.html
Make use of the fact that the majority element appears more than n/2 times. Keep track of the element value and count when looping the array. Increase the count each time when get the same value and decrease the count when get a different value. When the count is 0, change the value to the new element. Because the majority element appears more than n/2 times, the value kept after looping is always the majority element with count larger than 0.
int majorityElement(vector<int>& nums) {
int res = nums[0], cnt = 1;
for(int i=1; i<nums.size(); i++){
if(cnt == 0){
res = nums[i];
cnt = 1;
}
else if(nums[i] == res)
cnt++;
else
cnt--;
}
return res;
}
Solution 2. Use map to count for each element
int majorityElement(vector<int>& nums) {
unordered_map<int,int> m;
int mx = 0, res = 0;
for(int n: nums)
m[n]++;
for(auto const& x: m) {
if(mx < x.second) {
mx = x.second;
res = x.first;
}
}
return res;
}
No comments:
Post a Comment