Skip to main content

🟡 剑指 Offer II 060. 出现频率最高的 k 个数字

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

class Solution {    public int[] topKFrequent(int[] nums, int k) {        PriorityQueue<int[]> pq = new PriorityQueue<int[]>((x, y) -> {            return y[0] - x[0];        });
        Map<Integer, Integer> freq = new HashMap<>();        for (int num : nums) {            freq.put(num, freq.getOrDefault(num, 0)+1);        }
        for (var pair : freq.entrySet()) {            pq.offer(new int[]{pair.getValue(), pair.getKey()});        }
        int[] res = new int[k];
        for (int i=0; i<k; i++) {            res[i] = pq.poll()[1];        }
        return res;    }}