Leetcode 215. Kth Largest Element in an Array
Given an integer array nums
and an integer k
, return the k
th largest element in the array. Note that it is the k
th largest element in the sorted order, not the k
th distinct element.
Example:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
nums
contain negative numbers?
nums
can contain negative numbers.nums
be empty?
nums
will have at least one element.k
?
k
is always valid, which means 1 <= k <= nums.length
.k-1
.k
.k
.k
th largest element.k
th largest element without full sorting.Let’s implement the Min-Heap approach, which provides a good balance between simplicity and efficiency.
import java.util.PriorityQueue;
public class KthLargestElementInArray {
public int findKthLargest(int[] nums, int k) {
// Create a Min-Heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
for (int num : nums) {
minHeap.add(num);
// If the heap size exceeds k, remove the smallest element
if (minHeap.size() > k) {
minHeap.poll();
}
}
// The root of the heap is the k-th largest element
return minHeap.peek();
}
public static void main(String[] args) {
KthLargestElementInArray solution = new KthLargestElementInArray();
int[] nums1 = {3,2,1,5,6,4};
int[] nums2 = {3,2,3,1,2,4,5,5,6};
System.out.println(solution.findKthLargest(nums1, 2)); // Output: 5
System.out.println(solution.findKthLargest(nums2, 4)); // Output: 4
}
}
O(k)
time.n-k
elements, each insertion and removal operation in the heap takes O(log k)
time.O(n log k)
.This method is efficient and scales well for larger arrays compared to full sorting, which would take O(n log n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?