Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique.
桶排序是将数据划分出桶,放入有序的桶内,每个桶内分别进行排序,最后合并 桶排序的时间复杂度仅是On,非常快,但使用条件比较严格,首先数据必须能划分出桶来(比如数极差很大,接近INT_MAX,这时建有序桶就会消耗很大) 其次数据需要尽量分布均匀,不然桶排序相当于在一两个桶内排序,没意义。 讲解 https://blog.csdn.net/zihonggege/article/details/104781491
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
int max_count = 0;
for(int num : nums){
max_count = max(max_count, ++map[num]);
}
vector<vector<int>> buckets(max_count+1);
for(auto it : map){
buckets[it.second].push_back(it.first);
}
vector<int> res;
for(int i = buckets.size()-1; i >= 0 && res.size() < k; i--){
for(int num : buckets[i]){
res.push_back(num);
}
}
return res;
}
};
|