思路:快排或者堆
快排:
def findKthLargest(self, nums: List[int], k: int) -> int:
def partition(nums, left, right):
pivot = nums[left]
i, j = left, right
while i < j:
while i < j and nums[j] >= pivot:
j -= 1
while i < j and nums[i] <= pivot:
i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[j], nums[left] = nums[left], nums[j]
return j
left, right = 0, len(nums)-1
while True:
pivotIndex = partition(nums, left, right)
if pivotIndex == len(nums)-k:
return nums[pivotIndex]
elif pivotIndex < len(nums)-k:
left = pivotIndex+1
else:
right = pivotIndex-1
堆:
def findKthLargest(self, nums: List[int], k: int) -> int:
hp = [i for i in nums[:k]]
heapq.heapify(hp)
for i in nums[k:]:
if i > hp[0]:
heapq.heappop(hp)
heapq.heappush(hp, i)
return hp[0]