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白天的黑夜122 分钟前
链表-143.重排链表-力扣(LeetCode)
数据结构·leetcode·链表
cwplh2 小时前
Manacher(马拉车算法)详解
算法
快去睡觉~8 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
岁忧8 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
小欣加油8 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
月盈缺11 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
猿究院--王升11 小时前
jvm三色标记
java·jvm·算法
一车小面包11 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
科大饭桶12 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt55555555555513 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵