1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return self.quickSelect(nums, 0, len(nums) - 1, len(nums) - k + 1)
def quickSelect(self, nums, left, right, k): """ 在nums[left:right+1]中查找第k小的元素 """ if left == right: return nums[left]
pivot_index = self.partition(nums, left, right)
if pivot_index - left + 1 == k: return nums[pivot_index] elif pivot_index - left + 1 < k: return self.quickSelect(nums, pivot_index + 1, right, k - (pivot_index - left + 1)) else: return self.quickSelect(nums, left, pivot_index - 1, k)
def partition(self, nums, left, right): """ 对nums[left:right+1]进行分割,使得nums[left]左边的元素都小于等于nums[left],nums[left]右边的元素都大于等于nums[left] """ idx = random.randint(left, right); nums[left], nums[idx] = nums[idx], nums[left] pivot = nums[left] low, high = left, right while low < high: while low < high and nums[high] > pivot: high -= 1 if low < high: nums[low] = nums[high] low += 1 while low < high and nums[low] < pivot: low += 1 if low < high: nums[high] = nums[low] high -= 1 nums[low] = pivot return low
|