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;
    }
};
相关推荐
AI科技星17 小时前
接近光速运动下的光速不变性:基于张祥前统一场论的推导与验证
数据结构·人工智能·经验分享·算法·计算机视觉
陈苏同学18 小时前
笔记1.4:机器人学的语言——三维空间位姿描述 (旋转矩阵 - 齐次变换矩阵 - 欧拉角 - 四元数高效表示旋转)
笔记·线性代数·算法·机器人
scx2013100418 小时前
20251025 分治总结
数据结构·c++·算法
碧海银沙音频科技研究院19 小时前
DiVE长尾识别的虚拟实例蒸馏方法
arm开发·人工智能·深度学习·算法·音视频
居7然20 小时前
DeepSeek OCR:重新定义AI文档处理的“降本增效”新范式
人工智能·算法·语言模型·自然语言处理·大模型·ocr
while(1){yan}20 小时前
数据结构之堆
数据结构·python·算法
SleepyWhite00121 小时前
代码随想录Day61|Floyd 算法精讲、A * 算法精讲
算法·floyd算法·astar算法
Miraitowa_cheems21 小时前
LeetCode算法日记 - Day 84: 乘积为正数的最长子数组长度
数据结构·算法·leetcode·贪心算法·线性回归·深度优先·动态规划
不是老弟21 小时前
rwqsd
数据结构·c++·算法