力扣 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;
    }
};
相关推荐
DoraBigHead18 分钟前
小哆啦解题记——映射的背叛
算法
Heartoxx29 分钟前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者1 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7892 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价2 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七2 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战2 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说2 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
WebInfra2 小时前
如何在程序中嵌入有大量字符串的 HashMap
算法·设计模式·架构