1、用个hash表计数肯定没问题
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int>hash;
int res = 0, maxCnt = INT_MIN;
for(int i = 0; i < nums.size(); i++)
{
hash[nums[i]]++;
if(hash[nums[i]] > maxCnt)
{
maxCnt = hash[nums[i]];
res = nums[i];
}
}
return res;
}
};;
2、Boyer-Moore 投票算法:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int res = 0;
for(int i = 0; i < nums.size(); i++)
{
if(count == 0)
{
res = nums[i];
}
count += res == nums[i] ? 1 : -1;
}
return res;
}
};
参考:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/