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:
Idea: sort numbers and return (n/2)th element
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[floor(nums.size()/2)];
}
};
Solution:
Idea: randomly select one element and check its appliance time in the array. It runs faster.
<span style="font-size:14px;">class Solution {
public:
int majorityElement(vector<int>& nums) {
srand(unsigned(time(NULL)));
int n = nums.size();
while(true){
int elem = nums[rand()%n];
int counter = 0;
for(int i=0; i<n; i++){
if(nums[i]==elem)
counter++;
}
if (counter > n/2)
return elem;
}
}
};</span>
Solution:
Idea: hash table by using unordered_map
<span style="font-size:14px;">class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counter;
int n = nums.size();
int major;
for(int i=0; i<n; i++){
if(++counter[nums[i]]>n/2){
major = nums[i];
break;
}
}
return major;
}
};</span>