Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
nums = [3,2,1,5,6,4], k = 25nums = [3,2,3,1,2,4,5,5,6], k = 44PriorityQueue) of size kA min-heap of size k always holds the k largest elements seen so far. Its root is the smallest of those k — which is exactly the kth largest. When a new element comes in and pushes the heap to size k+1, we evict the minimum (root). This ensures we always keep the top-k candidates. At the end, the root is the answer.
Sorting the whole array and picking index n minus k works in O(n log n). But we only care about the top k values, not the full order.
Keep a min heap that holds at most k numbers. It always stores the k largest numbers seen so far. The smallest of those k sits at the root, so the root is the k-th largest so far. For every new number, push it, and if the heap grows beyond k, poll the root. At the end, the root is the answer.
For the k largest, use a min heap of size k. The root of that heap is the k-th largest.
Run the animation above on your own input, or watch the 1:51 video explanation of Kth Largest Element in an Array with a dry run and Java code.