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;
    }
};
相关推荐
kisshyshy12 小时前
🍦 雪糕、食堂、火车厢:三幅漫画吃透栈、队列与链表
javascript·算法
猿人谷20 小时前
不只是 CPU 阈值:STAR 如何用 GAT + Transformer 做容器级自动扩缩容?
人工智能·算法
复杂网络21 小时前
Stable Diffusion 视觉大模型微调技术深度调研
算法
复杂网络21 小时前
基于 Stable Diffusion 架构的视觉大模型代表性工作与原理深度解析
算法
MrZhao40021 小时前
Agent Loop 如何用 Hook 扩展:权限、日志与工具拦截
算法
MrZhao40021 小时前
Agent 为什么需要 Skills:别把所有知识都塞进 system prompt
算法
JieE2122 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2123 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack204 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树4 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色