The Kth Largest Element in an Array problem involves finding the K
th largest element in an unsorted array. This is commonly solved using a min-heap or the Quickselect algorithm.
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Step 1: Add elements to the heap
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll(); // Remove the smallest element
}
}
// Step 2: The root of the heap is the Kth largest element
return minHeap.peek();
}
}
O(N log K)
โ Adding and removing elements from the heap.O(N log K)
.Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Explanation:
- Add elements to the heap and maintain its size as K.
- The 2nd largest element is 5.
K
greater than the array size.K
is large.