0215. Kth Largest in Array
Medium | Array + Sort + QuickSelect | 40 ms (98.02%), 14.1 MB (94.93%)
Last updated
Was this helpful?
Medium | Array + Sort + QuickSelect | 40 ms (98.02%), 14.1 MB (94.93%)
Last updated
Was this helpful?
Soure: GitHub:
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.
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.