力扣-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()可以直接去重。

相关推荐
AlenTech1 分钟前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
练习时长一年1 小时前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
lzllzz231 小时前
bellman_ford算法
算法
栈与堆1 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
sunfove1 小时前
麦克斯韦方程组 (Maxwell‘s Equations) 的完整推导
线性代数·算法·矩阵
Rui_Freely1 小时前
Vins-Fusion之 SFM准备篇(十二)
人工智能·算法·计算机视觉
yyy(十一月限定版)2 小时前
matlab矩阵的操作
算法·matlab·矩阵
努力学算法的蒟蒻2 小时前
day58(1.9)——leetcode面试经典150
算法·leetcode·面试
txinyu的博客2 小时前
map和unordered_map的性能对比
开发语言·数据结构·c++·算法·哈希算法·散列表
搞笑症患者2 小时前
压缩感知(Compressed Sensing, CS)
算法·最小二乘法·压缩感知·正交匹配追踪omp·迭代阈值it算法