解题思路:
小根堆统计前K个高频元素
注意:
PriorityQueue中需要自定义排序规则
class Solution {public int[] topKFrequent(int[] nums, int k) {PriorityQueue<int[]> pq = new PriorityQueue<>((x,y)->x[1]-y[1]);Map<Integer,Integer> map=new HashMap<>();for(int num:nums){map.put(num,map.getOrDefault(num,0)+1);}for(Map.Entry<Integer,Integer> entry:map.entrySet()){if(pq.size()<k) pq.add(new int[]{entry.getKey(),entry.getValue()});else{if(entry.getValue()>pq.peek()[1]){pq.poll();pq.add(new int[]{entry.getKey(),entry.getValue()});}}}int[] res=new int[k];for(int i=0;i<k;i++){res[i]=pq.poll()[0];}return res;}
}