Problem
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.
You must solve it in O(n) time complexity.
Algorithm
Based on the quicksort algorithm.
Code
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def KthLargest(nums, k):
nlen = len(nums)
pivot = random.randint(0, nlen-1)
if pivot:
nums[pivot], nums[0] = nums[0], nums[pivot]
M = 0
for i in range(1, nlen):
if nums[i] >= nums[0]:
M += 1
nums[M], nums[i] = nums[i], nums[M]
nums[M], nums[0] = nums[0], nums[M]
if k == M:
return nums[M]
elif k < M:
return KthLargest(nums[0:M], k)
else:
return KthLargest(nums[M:], k - M)
return KthLargest(nums, k-1)