215_Kth Largest Element in an Array
Find the kth largest element in an unsorted array. There might be duplicates in the array.
Example 1:
Example 2:
Solution 1:
Idea:
Sort the array in descending order, then get the kth element.
Time Complexity:
Space Complexity:
Solution 2: ??
Idea:
store a candidate set of k elements in a min-heap
Time Complexity:
Space Complexity:
Solution 3
Idea:
Similar to quick sort
Randomly choose a pivot, store the elements less than the pivot, larger than the pivot and the number of duplicated pivot n.
If including some or all the pivot, the elements larger than (or equal to) the pivot can be k, then the pivot is the kth largest.
If less than k, the values in the larger group and pivot are not enough for kth largest, so we focus on the array with smaller values and find the next several largest.
If larger than k, focus on the larger group for the kth largest element.
Time Complexity:
Space Complexity: we can reduce the extra space to by in-place partition around the pivot.
Last updated