最大的K个元素 => 小根堆(类似上窄下宽的梯形)
最小的K个元素 => 大根堆(类似倒三角形)
法1:小根堆
java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> valToCountMap = new HashMap<>();
for (int i : nums) {
valToCountMap.put(i, valToCountMap.getOrDefault(i, 0) + 1);
}
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
for (Map.Entry<Integer, Integer> entry : valToCountMap.entrySet()) {
int val = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (count > queue.peek()[1]) {
queue.poll();
queue.offer(new int[]{val, count});
}
} else {
queue.offer(new int[]{val, count});
}
}
int[] res = new int[k];
for (int i = 0; i < k; ++i) {
res[i] = queue.poll()[0];
}
return res;
}
}