前 K 个高频元素 (Top K Frequent Elements)

 

思路:官方题解,优先级队列+hash

// @Title: 前 K 个高频元素 (Top K Frequent Elements)
// @Author: qisiii
// @Date: 2024-09-14 22:51:24
// @Runtime: 12 ms
// @Memory: 47.6 MB
// @comment: 官方题解,优先级队列+hash
// @flag: GREEN
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i:nums){
            map.put(i,map.getOrDefault(i,0)+1);
        }
        PriorityQueue<int[]> queue=new PriorityQueue<>(new Comparator<int[]>(){
            @Override
            public int compare(int[] m,int[] n){
                return m[1]-n[1];
            }
        });
        for(Map.Entry<Integer,Integer> entry:map.entrySet()){
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            if(queue.size()==k){
                int[] peek = queue.peek();
                if(peek[1]<value){
                    queue.poll();
                    queue.offer(new int[]{key,value});
                }
            }else {
                queue.offer(new int[]{key,value});
            }
        }
        int[] result=new int[k];
        while (!queue.isEmpty()){
            result[--k]=queue.poll()[0];
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18