题目:
思路:
用快速排序的基本思想。
在数组中随机选择一个数字pivot,然后调整数组中数字的顺序,使得比选中的数字小的数字都排在它左边,比选中的数字大的数字都排在它的右边。
- 如果选中的数字的下标刚好等于target = length-k,则这个数字就是第k大的;
- 如果选中的数字的下标刚好小于target,则第k大的数字位于这个数字右边;
- 如果选中的数字的下标刚好大于target,则第k大的数字位于这个数字左边。
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def __partition(nums, left, right):
pivot = nums[left]
j = left
for i in range(left + 1, right + 1):
if nums[i] < pivot:
j += 1
nums[i], nums[j] = nums[j], nums[i]
nums[left], nums[j] = nums[j], nums[left]
return j
def __check_invalid_array(nums):
return True if len(nums) <= 1 else False
if __check_invalid_array(nums):
return nums[0]
target = len(nums) - k
start = 0
end = len(nums) - 1
index = __partition(nums, start, end)
while(index != target):
if index > target:
end = index - 1
index = __partition(nums, start, end)
else:
start = index + 1
index = __partition(nums, start, end)
result = nums[target]
return result
- 其他思路待整理