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() {
        }
    }
}
相关推荐
Miraitowa_cheems5 分钟前
LeetCode算法日记 - Day 108: 01背包
数据结构·算法·leetcode·深度优先·动态规划
大千AI助手38 分钟前
平衡二叉树:机器学习中高效数据组织的基石
数据结构·人工智能·机器学习·二叉树·大模型·平衡二叉树·大千ai助手
九年义务漏网鲨鱼40 分钟前
【多模态大模型面经】现代大模型架构(一): 组注意力机制(GQA)和 RMSNorm
人工智能·深度学习·算法·架构·大模型·强化学习
闲人编程1 小时前
CPython与PyPy性能对比:不同解释器的优劣分析
python·算法·编译器·jit·cpython·codecapsule
杜子不疼.1 小时前
【C++】深入解析AVL树:平衡搜索树的核心概念与实现
android·c++·算法
小武~1 小时前
Leetcode 每日一题C 语言版 -- 88 merge sorted array
c语言·算法·leetcode
e***U8201 小时前
算法设计模式
算法·设计模式
是苏浙1 小时前
零基础入门C语言之C语言实现数据结构之栈
c语言·开发语言·数据结构
徐子童2 小时前
数据结构----排序算法
java·数据结构·算法·排序算法·面试题
hansang_IR2 小时前
【记录】四道双指针
c++·算法·贪心·双指针