力扣 347. 前 K 个高频元素

🔗 https://leetcode.cn/problems/top-k-frequent-elements

题目

  • 给一个数组,返回其中出现频率前 K 高的数字

思路

  • 统计数组中数字出现的频率
  • 优先队列,建立大小为 k 的小根堆,根据数字出现的频率排序
  • 更新并维护该优先队列,便是前 K 个高频元素

代码

cpp 复制代码
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (auto num : nums) {
            m[num]++;
        }

        auto minHeapCompare = [](pair<int, int> left, pair<int, int> right) {
		return left.second > right.second; // 自定义比较器,建立最小堆
};
std::priority_queue<pair<int, int>, std::vector<pair<int, int>>, decltype(minHeapCompare)>
            heap(minHeapCompare);

        for (auto item : m) {
            if (heap.size() < k) {
                pair<int, int> p = make_pair(item.first, item. second);
                heap.push(p);
                continue;
            }
            if (item.second > heap.top().second) {
                heap.pop();
                pair<int, int> p = make_pair(item.first, item. second);
                heap.push(p);
            }

            
        }

        vector<int> ans;
        while (heap.empty() == false) {
            ans.push_back(heap.top().first);
            heap.pop();
        }
        return ans;
    }
};
相关推荐
君万12 分钟前
【LeetCode每日一题】94. 二叉树的中序遍历 104. 二叉树的最大深度
算法·leetcode·golang
Imxyk13 分钟前
力扣:2322. 从树中删除边的最小分数
数据结构·算法·leetcode
农场主John15 分钟前
(双指针)LeetCode 209 长度最小的子数组
数据结构·算法·leetcode
程序员Xu15 分钟前
【LeetCode热题100道笔记】前 K 个高频元素
笔记·算法·leetcode
Asmalin16 分钟前
【代码随想录day 23】 力扣 93.复原IP地址
算法·leetcode
AMiner:AI科研助手2 小时前
警惕!你和ChatGPT的对话,可能正在制造分布式妄想
人工智能·分布式·算法·chatgpt·deepseek
CHANG_THE_WORLD6 小时前
并发编程指南 同步操作与强制排序
开发语言·c++·算法
gaoshou457 小时前
代码随想录训练营第三十一天|LeetCode56.合并区间、LeetCode738.单调递增的数字
数据结构·算法
自信的小螺丝钉7 小时前
Leetcode 240. 搜索二维矩阵 II 矩阵 / 二分
算法·leetcode·矩阵
KING BOB!!!8 小时前
Leetcode高频 SQL 50 题(基础版)题目记录
sql·mysql·算法·leetcode