Partition方法(同向/雙向雙指針)解決 215. Kth Largest Element in an Array

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章