【优先队列】LeetCode 347. 前 K 个高频元素
题目链接
思路
前k大模板题
代码
class Solution{
public int[] topKFrequent(int[] nums, int k){
PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>(
new Comparator<Map.Entry<Integer, Integer>>(){
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){
return Integer.compare(o1.getValue(), o2.getValue());
}
});
Map<Integer, Integer> map = new HashMap<>();
for(Integer num : nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
priorityQueue.add(entry);
if(priorityQueue.size() > k){
priorityQueue.poll();
}
}
int[] result = new int[k];
for(int i = 0; i < k; i++){
result[i] = priorityQueue.poll().getKey();
}
return result;
}
}