最常用的k个元素 347. Top K Frequent Elements
用max heap
// use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency
public class Solution {
public List topKFrequent(int[] nums, int k) {
Map map = new HashMap<>();
for(int n: nums){
map.put(n, map.getOrDefault(n,0)+1);
}
PriorityQueue> maxHeap =
new PriorityQueue<>((a,b)->(b.getValue()-a.getValue()));
for(Map.Entry entry: map.entrySet()){
maxHeap.add(entry);
}
List res = new ArrayList<>();
while(res.size()<k){
Map.Entry entry = maxHeap.poll();
res.add(entry.getKey());
}
return res;
}
}