1. quickselect. (相向双指针)。原理和partition里讲的一样。
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return self.quickselect(nums,0,len(nums)-1,k)
def quickselect(self,nums,start,end,k):
pivot=nums[start]
i,j=start,end
while (i<=j):
while i<=j and nums[i]>pivot:
i += 1
while i<=j and nums[j]<pivot:
j -= 1
if i<=j:
nums[i],nums[j]=nums[j],nums[i]
i += 1
j -= 1
if (start+k-1<=j):
return self.quickselect(nums,start,j,k)
if (start+k-1>=i):
return self.quickselect(nums,i,end,k+start-i)
return nums[j+1]
2. also partition,同向双指针. 这个partition函数每次都把最大的数往右排,pivot是nums[-1]。如果要找第2大的数,那么return index要等于len(nums)-k. 比如在[5,7,4,1,6]找第3th largest,那么index就是2(要有三个数在index以及之后)。如果一次partition return的index<len(nums)-k, 那么说明找的太多了,start=index+1减少查找区间。如果index>len(nums)-k,说明找的少了,要从更小的地方继续找于是end=index-1。search recursively till index==len(nums)-k
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if len(nums) < k:
return -1
start = 0
end = len(nums) - 1
index = self.partition(nums, start, end)
while index != len(nums) - k:
if index > len(nums) - k:
end = index - 1
else:
start = index + 1
index = self.partition(nums, start, end)
return nums[index]
def partition(self, nums, start, end):
pivot = nums[end]
index = start
for i in range(start, end):
if nums[i] > pivot:
continue
nums[index], nums[i] = nums[i], nums[index]
index += 1
nums[index], nums[end] = nums[end], nums[index]
return index