利用快排的思想求解数组中第K大的元素.
类似二分查找的思路,
需要注意的是,划分数组的时候,需要将左边改为大于pivot的值
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if k > len(nums) or len(nums) < 1:
return -1
left = 0
right = len(nums)-1
while 1:
mid = self.partition(nums, left, right)
# print('left,right,mid', left,right,mid)
if mid == k-1:
return nums[mid]
elif mid > k-1:
right = mid - 1
else:
left = mid + 1
return -1
def partition(self, nums, start, end):
pivot = nums[end]
i = start
for j in range(start, end):
if nums[j] > pivot:
nums[j], nums[i] = nums[i], nums[j]
i += 1
nums[i], nums[end] = nums[end], nums[i]
return i
网友评论