我的解决方法:
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
int total=1;
int i;
for(i=1;i<nums.size();i++){
if(nums[i]!=nums[i-1]){
total = 1;
}else{
total++;
}
if(total>nums.size()/2){
break;
}
}
return nums[i];
}
};
测试样例能过,但是submit时会提示run time error。
分析:vector的sort是O(nlogn),已经很大了,我又搞了个O(n)的判定,加起来可能超过了时间限制。
以下是几种方法:
1.Sorting
虽然也是排序,但是这种方法直接返回排序后的序列的中间值,这个中间值必定是最大的。
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
return nums[n/2];
}
};
2.Hashmap
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
unordered_map<int, int> m;
for(int i = 0; i < n; i++){
m[nums[i]]++;
}
n = n/2;
for(auto x: m){
if(x.second > n){
return x.first;
}
}
return 0;
}
};
空间复杂度稍高一点,但是时间复杂度为O(n)
3.Moore Voting Algorithm
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
if (num == candidate) {
count++;
} else {
count--;
}
}
return candidate;
}
};
这个算法的思想比较巧妙:如果一个数能占到一半以上,那么它最后出现的次数能够保持正数,即使减去其他的元素出现的次数。