首页 > 其他 > 详细

分治法学习

时间:2020-08-09 23:34:01      阅读:85      评论:0      收藏:0      [点我收藏+]

经典分治:

215. 数组中的第K个最大元素

题解: 使用快排的思想找第 K 大, 如果当前的下标 pivot == k , 那么我们找到了对应的元素;如果pivot>k ,那么要寻找的元素在pivot左边;如果pivot<k,那么要寻找的元素在pivot右边。

class Solution(object):

    
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """

        def partition(l, r):
            pivot = nums[l]
            while l<r:
                while l<r and nums[r] <= pivot:
                    r-=1
                nums[l] = nums[r]
                while l<r and nums[l] >= pivot:
                    l+=1
                nums[r] = nums[l]
            nums[l] = pivot
            return l
        def find_K(l, r , k):
            if l>r: return
            pivot = partition(l, r)
            if pivot==k: return
            if k < pivot: 
                find_K(l, pivot-1, k)
            else:
                find_K(pivot+1, r, k)
        k-=1
        find_K(0, len(nums)-1, k)
        return nums[k]

 

技术分享图片

 

分治法学习

原文:https://www.cnblogs.com/liyinggang/p/13466701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!