当前位置 博文首页 > 中流击水,浪遏飞舟:摩尔投票法&&哈希&&剑指 O
O(n)时间复杂度。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int>count;
int length=nums.size()/2;
for(auto x:nums){
count[x]++;
}
for(auto y:count){
if(y.second>length){
return y.first;
}
}
return 0;
}
};
O(1)时间复杂度。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ans=0,count=0;
for(auto x:nums){
if(count==0){
ans=x;
count++;
}
else{
ans==x?count++:count--;
}
}
return ans;
}
};
cs