Count, then min-heap of size k
Time O(n log k) Space O(n)Count frequencies. Push each distinct value into a min-heap ordered by count; if the heap grows past k, remove the least frequent. The heap ends with the k most frequent.
import java.util.*;
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) count.merge(x, 1, Integer::sum);
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> Integer.compare(count.get(a), count.get(b)));
for (int v : count.keySet()) {
heap.offer(v);
if (heap.size() > k) heap.poll();
}
int[] out = new int[k];
for (int i = 0; i < k; i++) out[i] = heap.poll();
return out;
}
}Verdict: Good when k is small; the Heaps module covers this Top-K pattern in depth.