[LeetCode]215. Kth Largest Element in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37422289/article/details/80538243

找到数组中第k大的数
215. Kth Largest Element in an Array

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        target = len(nums) - k
        low, high = 0 , len(nums)-1
        while low < high:
            l,r = low, high
            p = nums[l]
            while l < r:
                while l < r and nums[r] >= p:
                    r -= 1
                nums[l] = nums[r]
                while l < r and nums[l] <= p:
                    l += 1
                nums[r] = nums[l]
            nums[l] = p
            if l == target:
                return p
            elif l < target:
                low, high = l+1, high
            else:
                low, high = low, l-1
        return nums[low]

猜你喜欢

转载自blog.csdn.net/m0_37422289/article/details/80538243