1.Description
Given an array nums of size n, return the majority element which appears more than n/2 times. And the majority element always exists.
2.Algorithms
Moore Voting O(n)
3.Analysis
Sort
At first, I tried quick sort algorithm. But its time complexity doesn’t meet the requirement.
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
int times = floor(nums.size()/2);
int cnt = 1;
int a = nums[0];
for(int i = 1;i < nums.size();i++){
if(a != nums[i]){
if(cnt > times){
return {a};
}
else{
a = nums[i];
cnt = 0;
}
}
cnt++;
}
if(cnt > times) return {a};
return 0;
}
};
And there is a detail to optimize the code. Because the majority element appears more than n/2 times, after sorting, nums[n/2] must be the element we want. So it can be optimized like this.
class Solution {
public:
int majorityElement(vector<int>& nums) {
if(nums.size() == 1) return nums[0];
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
Moore Voting
This algorithm can only be used when the majority element exists.
The core idea is that the number of different elements cancel each other out. ‘cnt == 0‘ means that the different elements that have been iterated so far have the same number of occurrence.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 1, ans = 0;
for(int i = 1;i < nums.size();i++){
if(nums[i] != nums[ans])
cnt--;
else
cnt++;
if(cnt == 0){
ans = i;
cnt++;
}
}
return nums[ans];
}
};
4. Complexity
sort
Time complexity: O(nlogn)
Space complexity: O(1)
Moore Voting
Time complexity: O(n)
Space complexity: O(1)