n-low=k,返回a[low]
n-low>k,递归遍历右边的序列,n-low<k遍历左边的序列
把数组分成两部分,一部分小于一个值,另一部分大于这个值(temp),假设temp此时是数组第i个数,如果i=k,temp就是数组的第i个数。
如果i=k,那么temp就是第k大;如果i<k,k就在数组右边,继续在右边查找;如果i>k,k就在数组左边,就在左边查找。循环往复:
# -*- coding:utf-8 -*-
class Solution:
def findKth(self, a, n, K):
# write code here
if n<= 1:
return a[0]
a = self.quickSort(a, 0, n-1, K)
return a[n-K]
def quickSort(self, a, start, end, k):
if start>=end:
return
low = start
high = end
temp =a[start]
while low<high:
while a[high]>=temp and low<high:
high -= 1
a[low] = a[high]//这里不可以缩进,不然进入循环后出不来,影响时间限制
while a[low] < temp and low < high:
low += 1
a[high] = a[low]
a[low] = temp
self.quickSort(a,low+1, end ,k)
self.quickSort(a,start, low ,k)
return a

京公网安备 11010502036488号