Leetcode 347. 前 K 个高频元素 堆 / 优先队列

原题链接:Leetcode 347. 前 K 个高频元素

进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。

1. 堆 / 优先队列

cpp 复制代码
class Solution {
public:
    struct cmp{
        bool operator() (const pair<int,int>& a, const pair<int,int>& b){
            return a.second > b.second; // 小顶堆
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> count;
        for(auto x: nums) count[x]++;
         // pair 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
        priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> q;
        for(auto x: count){
            int num = x.first;
            int cnt = x.second;
            if(q.size()==k){
                if(q.top().second < cnt){
                    q.pop();
                    q.push({num,cnt});
                }
            }
            else{
                q.push({num,cnt});
            }
        }
        vector<int> res;
        while(!q.empty()){
            int num = q.top().first;
            res.push_back(num);
            q.pop();
        }
        return res;
    }
};
相关推荐
疯狂的喵5 小时前
C++编译期多态实现
开发语言·c++·算法
scx201310045 小时前
20260129LCA总结
算法·深度优先·图论
2301_765703145 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708055 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习6 小时前
【算法——c/c++]
c语言·c++·算法
智码未来学堂6 小时前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
春日见7 小时前
如何避免代码冲突,拉取分支
linux·人工智能·算法·机器学习·自动驾驶
副露のmagic7 小时前
更弱智的算法学习 day59
算法
u0109272717 小时前
C++中的RAII技术深入
开发语言·c++·算法