方法一、排序找众数(只适合众数的个数大于n/2的情况)
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
方法二、哈希
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> hash;
int maxn = 0, maxIndex = 0;
for(int i = 0; i < nums.size(); i++) {
hash[nums[i]]++;
}
//取哈希hash里的value中的最大值
for(auto& x: hash) {
if(maxn < x.second) {
maxn = x.second;
maxIndex = x.first;
}
}
return maxIndex;
}
};