1、哈希表
int majorityElement(vector<int>& nums) {
int n = nums.size();
map<int, int> m;
for (int i = 0; i < n; i++) {
if (m.find(nums[i]) == m.end())
m[nums[i]] = 1;
else {
m[nums[i]]++;
}
if (m[nums[i]] > n / 2)
return nums[i];
}
return - 1;
}
2、Boyer-Moore 投票算法
int majorityElement(vector<int>& nums) {
int n = nums.size();
int res;
int count = 0;
for (int i = 0; i < n; i++) {
if (count == 0) {
res = nums[i];
count++;
}
else if(nums[i]==res){
count++;
}
else {
count--;
}
}
return res;
}
方法二参考力扣官方题解