获取数组中频数最多的K个数字
采用map统计每个数字的频数,然后进行K次遍历,每次遍历取出频数最大的数字,并删除。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> temp;
for(auto num:nums)temp[num]++;
vector<int> res;
for(int i=0; i<k; i++){
int max=0, num;
map<int, int>::iterator iter;
iter = temp.begin();
while(iter != temp.end()) {
if(iter->second > max){
max = iter->second;
num = iter->first;
}
iter++;
}
res.push_back(num);
temp.erase(num);
}
return res;
}
};