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.
Solution 1:
Using hash table:
Using hash table:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int majorityElement(vector<int>& nums) { | |
unordered_map<int, int> myMap; | |
for(int i=0; i<nums.size(); i++){ | |
myMap[nums[i]]=myMap[nums[i]]+1; | |
if(myMap[nums[i]]>int(nums.size())/2) | |
return nums[i]; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int majorityElement(int[] num) { | |
int major=num[0], count = 1; | |
for(int i=1; i<num.length;i++){ | |
if(count==0){ | |
count++; | |
major=num[i]; | |
}else if(major==num[i]){ | |
count++; | |
}else count--; | |
} | |
return major; | |
} | |
} |
Actually there are many other solutoins, please see: Here
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int majorityElement(vector<int>& nums) { | |
int cnt=1; | |
int num=nums[0]; | |
for(int i=1; i<nums.size(); i++){ | |
if(nums[i]==num) | |
cnt++; | |
else | |
if(--cnt==0){ | |
num=nums[i]; | |
cnt=1; | |
} | |
} | |
return num; | |
} | |
}; |
No comments:
Post a Comment