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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值