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;
    }
};
相关推荐
怕浪猫7 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记7 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_38 小时前
二叉树の递归遍历
算法
All for pursuit.8 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉9 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
一只小小的芙厨11 小时前
【线性DP】
学习·算法·动态规划
奋发向前wcx11 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
罗湖老棍子13 小时前
C Looooops(信息学奥赛一本通- P1640)
算法·数论·同余·裴蜀定理·扩展欧几里得
飘尘15 小时前
从"算子"到"AI Infra":大模型背后看不见的那群人在忙什么
人工智能·算法·面试
夏幻灵16 小时前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展