桶排序
前 K 个高频元素
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> num_cnt;
for(auto num:nums){
num_cnt[num]++;
}
vector<vector<int>> buckets(nums.size()+1);
for(auto nc:num_cnt){
buckets[nc.second].push_back(nc.first);
}
int i = nums.size();
vector<int> res;
// Continue until we fetch exactly k elements
while (k > 0 && i > 0) {
if (!buckets[i].empty()) {
for (auto b : buckets[i]) {
res.push_back(b);
k--;
}
}
i--;
}
return res;
}
};
关键在于使用桶排序,还有需要确定while循环的退出条件,我这里设置i和k都要大于0,频率为0的不需要去检验