力扣-347.前K个高频元素

题目链接

347.前K个高频元素

java 复制代码
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        Set<Integer> set = map.keySet();
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o2) - map.get(o1);
            }
        });
        for (Integer i : set) {
            queue.offer(i);
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = queue.poll();
        }
        return res;
    }
}

小结:优先级队列,注意用map.keySet()可以直接去重。

相关推荐
海琴烟Sunshine1 小时前
Leetcode 26. 删除有序数组中的重复项
java·算法·leetcode
PAK向日葵1 小时前
【算法导论】NMWQ 0913笔试题
算法·面试
PAK向日葵1 小时前
【算法导论】DJ 0830笔试题题解
算法·面试
PAK向日葵1 小时前
【算法导论】LXHY 0830 笔试题题解
算法·面试
麦麦麦造2 小时前
DeepSeek突然发布 V3.2-exp,长文本能力加强,价格进一步下探
算法
lingran__3 小时前
速通ACM省铜第十七天 赋源码(Racing)
c++·算法
MobotStone3 小时前
手把手教你玩转AI绘图
算法
CappuccinoRose4 小时前
MATLAB学习文档(二十二)
学习·算法·matlab
学c语言的枫子5 小时前
数据结构——基本查找算法
算法
yanqiaofanhua5 小时前
C语言自学--自定义类型:结构体
c语言·开发语言·算法