题目链接:LeeCode347前k个高频元素
题目描述:
优先队列维护小根堆,每次有比队首大的就弹出队首然后入队
class Solution {
public static int[] topKFrequent(int[] nums, int k) {
int[] frequent=new int[k];
Map<Integer,Integer> map=new HashMap<>();
//小根堆,即按比较器中内容升序排列,该题中则为按出现次数升序排列
PriorityQueue<Integer> pq=new PriorityQueue(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return map.get(o1)-map.get(o2);
}
});
//统计次数
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i]))map.put(nums[i],map.get(nums[i])+1);
else map.put(nums[i],1 );
}
//维护小根堆
for (Integer integer : map.keySet()) {
if(pq.size()<k){
pq.offer(integer);
}else{
if(map.get(pq.peek())<map.get(integer)){
pq.poll();
pq.offer(integer);
}
}
}
//倒叙存放
for (int i = k-1; i >=0; i--) {
frequent[i]=pq.poll();
}
return frequent;
}
}