前 K 个高频元素
题目链接:前 K 个高频元素
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
方法一:桶排序
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> cnt;
int max_cnt = 0;
for (int x : nums) {
cnt[x]++;
max_cnt = max(max_cnt,cnt[x]);
}
vector<vector<int>> buckets(max_cnt+1);
for (auto& [x,c] : cnt) {
buckets[c].push_back(x);
}
vector<int> ans;
for (int i = max_cnt;i >= 0 && ans.size() < k;i--) {
ans.insert(ans.end(),buckets[i].begin(),buckets[i].end());
}
return ans;
}
};