0215. Kth Largest in Array
Medium | Array + Sort + QuickSelect | 40 ms (98.02%), 14.1 MB (94.93%)
Soure: LeetCode - Kth Largest Element in an Array GitHub: Solution / Performance
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.
Do quick sort to put larger elements on the left of the selected pivot.
For quick sorting, we need a partition function based on the randomly selected pivot index to divide the array into two parts:
The left part contains larger elements (> randomly-selected pivot)
The right part contains smaller elements (< randomly-selected pivot)
Since the partition function returns n-th largest index, the quick soring ends whenn == k
. Otherwise, we modify the range between left and right for the next partition.
Last updated