leedcode 数组中的第K大元素

1.快速排序法

选择基准元素,基准元素左边的元素均大于该元素,基准元素右边的元素均小于该元素,如果基准元素左边的数量大于K,则在基准元素的左边查找,否则在基准元素右边查找,知道找到第K大基准元素。

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        low = 0
        high = len(nums) - 1
        mid = 0
        while low <= high:
            mid = self.partition(nums, low, high)
            if mid == k - 1:
                return nums[mid]
            if mid > k - 1:
                high = mid - 1
            if mid < k - 1:
                low = mid + 1
        return -1
    def partition(self, nums, low, high):
        left = low + 1
        right = high
        bound = nums[low]
        while left <= right:
            while (left <= right) and (nums[left] >= bound):left += 1
            while nums[right] < bound:right = right - 1
            if left < right:
                temp = nums[left]
                nums[left] = nums[right]
                nums[right] = temp
            else:
                break
        nums[low] = nums[right]
        nums[right] = bound
        return right

2.大根堆

先将数据构造成大根堆,然后在依据堆排序,依次取出前k个数据,第K个数据就是数组的第K大元素。

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if len(nums) == 1 and k == 1:
            return nums[0]
        nums.insert(0, 0)
        len_nums = len(nums) - 1
        for i in range(len_nums // 2, 0, -1):
            self.AdjustDown(nums, i, len_nums)
        j = len_nums
        num = 0
        max_k_num = -1
        while j >= 1:
            max_k_num = nums[1]
            num += 1
            if num == k:
                break
            temp = nums[1]
            nums[1] = nums[j]
            nums[j] = temp
            self.AdjustDown(nums, 1, j - 1)
            j = j - 1
        return max_k_num        
            
    def AdjustDown(self, nums, k, len_nums):
        nums[0] = nums[k]
        i = 2 * k
        while i <= len_nums:
            if i < len_nums and nums[i] < nums[i + 1]:
                i += 1
            if nums[0] >= nums[i]:
                break
            else:
                nums[k] = nums[i]
                k = i
            i = i * 2
        nums[k] = nums[0]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值