美文网首页
215. Kth Largest Element in an A

215. Kth Largest Element in an A

作者: 羲牧 | 来源:发表于2020-07-12 21:14 被阅读0次

    利用快排的思想求解数组中第K大的元素.
    类似二分查找的思路,
    需要注意的是,划分数组的时候,需要将左边改为大于pivot的值

    class Solution:
        def findKthLargest(self, nums: List[int], k: int) -> int:
            if k > len(nums) or len(nums) < 1:
                return -1
            left = 0
            right = len(nums)-1
            while 1:
                mid = self.partition(nums, left, right)
                # print('left,right,mid', left,right,mid)
                if mid == k-1:
                    return nums[mid]
                elif mid > k-1:
                    right = mid - 1
                else:
                    left = mid + 1
            return -1
                
            
        
        def partition(self, nums, start, end):
            pivot = nums[end]
            i = start
            for j in range(start, end):
                if nums[j] > pivot:
                    nums[j], nums[i] = nums[i], nums[j]
                    i += 1
            nums[i], nums[end] = nums[end], nums[i]
            return i
            
        
            
    

    相关文章

      网友评论

          本文标题:215. Kth Largest Element in an A

          本文链接:https://www.haomeiwen.com/subject/nkbncktx.html