这题我就只写哈希表的方法,其他解题方法可看这里
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int>counts;
int majority = 0, cnt = 0;
for (int num : nums) {
++counts[num];
if (counts[num] > cnt) {
majority = num;
cnt = counts[num];
}
}
return majority;
}
};