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 the 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
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
The simplest and most direct way to find the k-th largest element is to sort the array first. Once sorted, the k-th largest can be easily accessed by indexing.
Instead of sorting the entire array, we can use a min-heap to maintain the k largest elements and efficiently find the k-th largest.
Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is based on the QuickSort algorithm. Instead of recursing both sides of the pivot, we only recurse into the part that contains the k-th element.
n-k, return its value.