23.02.28 学习
看代码吧,还是比较容易的
class Solution {
public:
// 哈希表+大根堆,统计出次数最多的前k个数的下界
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hash;
vector<int> res;
for (auto x : nums) hash[x] ++ ;
priority_queue<pair<int, int>> heap;
for (auto x : hash) heap.push({x.second, x.first});
for (int i = 0; i < k; i ++ ) {
res.push_back(heap.top().second);
heap.pop();
}
return res;
}
};