Min-heap of size k
Time O(log k) per add Space O(k)Offer each value; if the heap exceeds k, poll. peek() is the k-th largest.
import java.util.PriorityQueue;
class KthLargest {
private final PriorityQueue<Integer> pq = new PriorityQueue<>();
private final int k;
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) add(x);
}
public int add(int val) {
pq.offer(val);
if (pq.size() > k) pq.poll();
return pq.peek();
}
}Verdict: The top-K pattern exactly.