Here is the implementation using QuickSelect:
function findKthLargest(nums, k):
target = nums.length - k
return quickSelect(nums, 0, nums.length - 1, target)
function quickSelect(nums, left, right, target):
pivotIdx = partition(nums, left, right)
if pivotIdx == target:
return nums[pivotIdx]
else if pivotIdx < target:
return quickSelect(nums, pivotIdx + 1, right, target)
else:
return quickSelect(nums, left, pivotIdx - 1, target)
Average time, worst case . Use random pivot to avoid worst case. Space is (excluding input) with tail recursion.