Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
- Time: O(klog(n))
- Space: O(n)
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq =
new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < nums.length; i++) {
pq.offer(nums[i]);
}
while (k-- > 1) {
pq.poll();
}
return pq.peek();
}