求众数,主要想到的是采用hash_map的方法,顺便复习了下map 和hash_map的区别。下面一篇blog有详述。
https://blog.csdn.net/zishengzheng/article/details/81750332
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> k;
for(int i = 0; i < nums.size(); i++) k[nums[i]]++;
int max = 0;
int max_index = 0;
for(int i = 0; i < nums.size(); i++) {
max = max > k[nums[i]] ? max: k[nums[i]];
max_index = max > k[nums[i]] ? max_index: nums[i];
}
return max_index;
}
};