排序算法 桶排序 347. Top K Frequent Elements

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]);
        }
        //从0到max_count,每个出现次数建立一个桶
        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;
    }
  
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值