215. Kth Largest Element in an Array
#array #quick_select
Solution 1 (using sorting)
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}Solution 2 (using heap)
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for ( int i = 0; i < nums.length; ++i) {
minHeap.add(nums[i]);
// to ensure we keep the K smallest element
if (minHeap.size() > k) {
minHeap.remove();
}
}
return minHeap.peek();
}Last updated