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;
    }
};
相关推荐
yyds_yyd_100865 分钟前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
Chen—LSN13 分钟前
C语言——深度理解指针(5)
c语言·数据结构·算法·排序算法
佳児素花痴╮2 小时前
树的基础知识与查找排序算法
数据结构·算法
lueluelue479 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水16812 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
huameinan狮子12 小时前
Adaboost算法原理与计算实例
算法
别怪我很水12 小时前
API中提供了VelocityTracker类用于计算触摸事件MotionEvent的速度,而其内部默认使用的方法就是最小二乘法,本 ...
算法·gitee·最小二乘法
Re.不晚15 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
蓝悦无人机15 小时前
《Planning algorithms》读书笔记——第1章 引言
算法·读书笔记·规划算法·lavalle