1、肯定是用unordered_map啦!因为官方已经说了存在多数元素,就不用判断了。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> count;
int max_count=0, max_num=0;
for(int num: nums){
count[num]++;
if(count[num]>max_count){
max_count = count[num];
max_num = num;
}
}
return max_num;
}
};