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 sorted order, not the kth distinct element.
Can you solve it without sorting?
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Sorted: [1,2,3,4,5,6]
2nd largest = 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Sorted: [1,2,2,3,3,4,5,5,6]
4th largest = 4
Three Approaches:
Min-heap approach: Similar to "Kth Largest in Stream"!
This is a Top-K Selection problem:
Time: O(n log k) - better than sorting when k is small
Based on quicksort partition:
Time: O(n) average, O(n²) worst case
Sort array, return nums[n-k]
Time: O(n log n)
Time: O(n log k)
Space: O(k)
Best choice depends on:
1import java.util.PriorityQueue;
2
3class Solution {
4 public int findKthLargest(int[] nums, int k) {
5 // Min-heap of size k
6 PriorityQueue<Integer> minHeap = new PriorityQueue<>();
7
8 // Add first k elements
9 for (int i = 0; i < k; i++) {
10 minHeap.offer(nums[i]);
11 }
12
13 // Process remaining elements
14 for (int i = k; i < nums.length; i++) {
15 if (nums[i] > minHeap.peek()) {
16 minHeap.poll();
17 minHeap.offer(nums[i]);
18 }
19 }
20
21 // Root is kth largest
22 return minHeap.peek();
23 }
24}
25