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() {
        }
    }
}
相关推荐
a东方青7 分钟前
[16届蓝桥杯 2025 c++省 B] 移动距离
c++·算法·蓝桥杯
FAREWELL0007523 分钟前
C#进阶学习(一)简单数据结构类之ArrayList、Stack、Queue、Hashtable
数据结构·学习·c#·queue·arraylist·stack·hash table
烁3471 小时前
每日一题(小白)暴力娱乐篇25
java·数据结构·算法·娱乐
烁3471 小时前
每日一题(小白)暴力娱乐篇26
java·开发语言·算法·娱乐
学c++的一天1 小时前
蓝桥杯备战
算法·职场和发展·蓝桥杯
梭七y1 小时前
【力扣hot100题】(096)多数元素
算法·leetcode·职场和发展
zero.cyx3 小时前
蓝桥杯 DFS
算法·蓝桥杯·深度优先
码媛3 小时前
A002-随机森林模型实现糖尿病预测
算法·随机森林·机器学习
ricky_fan4 小时前
Leetcode39:组合总和——回溯算法
开发语言·c++·leetcode
爱看烟花的码农4 小时前
LeetCode 热题 8/100打卡
c++·python·算法·leetcode