前K个高频元素(topK)-排序347-c++

这篇博客介绍了两种不同的方法来找出数组中出现频率最高的k个元素。第一种方法利用了unordered_map和multimap,通过统计元素出现次数并按频率降序排列。第二种方法采用小顶堆,通过维护一个大小不超过k的优先队列来实时更新频率最高的元素。两种方法都有效地解决了问题。
摘要由CSDN通过智能技术生成

算法思想

没有用到很复杂的算法思想,就是利用了unordered_map和multimap各自的特点:

  • 创建统计数字出现次数的无序哈希表hashmap;
  • 将hashmap中的pair的second和first调换(即出现次数变成关键字,数值变成关键字对应的值),添加到可重复(可重复的原因:有些数值出现的次数可能相同)关键字的有序(greater是按大到小排序)哈希表ordermap中;
  • 将ordermap中前k个pair的值添加到输出数组res中,即可得到最终输出。

C++

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> hashmap;
        multimap<int, int, greater<int>> ordermap;
        vector<int> res;
        for (auto & v : nums){
            hashmap[v]++;
        }
        for(auto & ech : hashmap){
            ordermap.insert(pair<int, int>(ech.second, ech.first));
        }
        for(auto & ech : ordermap){
            res.push_back(ech.second);
            k--;
            if(k == 0) break;
        }
        return res;
    }
};

小顶堆思想

class Solution {
public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
        // 哈希表记录数字出现次数
        // 优先队列,按照次数排序,小顶堆(每次想弹出谁,就建什么堆),保证size不大于k
        vector<int> res;
        unordered_map<int, int> count_map;
        for (auto& num : nums) {
            count_map[num]++;
        }
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

        for(auto& it : count_map) {
            pq.push(make_pair(it.second, it.first));
            if (pq.size() > k) {
                pq.pop();
            }
        }

        for (int i = 0; i < k; i++) {
            res.emplace_back(pq.top().second);
            pq.pop();
        }

        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值