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() {
        }
    }
}
相关推荐
大闲在人5 分钟前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋8 分钟前
443. 压缩字符串-python-双指针
算法
Charlie_lll18 分钟前
力扣解题-移动零
后端·算法·leetcode
chaser&upper19 分钟前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_4997715527 分钟前
C++中的组合模式
开发语言·c++·算法
iAkuya1 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
近津薪荼1 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck1 小时前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl
松☆1 小时前
CANN与大模型推理:在边缘端高效运行7B参数语言模型的实践指南
人工智能·算法·语言模型
java干货1 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法