75、堆-前K个高频元素

思路

这道题还是使用优先队列,是要大根堆,然后创建一个类,成员变量值和次数。大根堆基于次数排序。前k个就拿出前k的类的值即可。代码如下:

复制代码
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
            return null;
        }
        int[] ans = new int[k];
        PriorityQueue<Info> priorityQueue = new PriorityQueue<>((o1, o2) -> o2.times - o1.times);
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        map.forEach((value, times) -> {
            Info info = new Info();
            info.times = times;
            info.value = value;
            priorityQueue.add(info);
        });

        for (int i = 0; i < k; i++) {
           ans[i] = priorityQueue.poll().value;
        }
        return ans;
    }

    class Info {
        public int times;
        public int value;

        public Info() {
        }
    }
}
相关推荐
程序员清风1 小时前
算法题中的边界条件、测试与调试
开发语言·算法·kotlin
炘爚1 小时前
数据结构算法总结
数据结构·python·算法
Dageno_AI2 小时前
ChatGPT 不再引用 Reddit 之后,还值得在 Reddit 上做 AI 可见度吗?
算法
hetao17338372 小时前
2026-10-25 hetao1733837 的刷题记录
c++·算法
Jsundoku2 小时前
第七章 机器学习 -- 其他经典算法
人工智能·算法·机器学习
进击的丸子2 小时前
基于 ArcFace SDK 的跨平台人脸特征值下发、同步以及存储方案
后端·算法·代码规范
见叶之秋2 小时前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试
kiracrimson3 小时前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
一条闲鱼_mytube3 小时前
分布式 ID 生成方案:雪花算法与号段模式
分布式·算法·wpf
Msir_Modern3 小时前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机