LeetCode215.Kth Largest Element in an Array

题目:

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

思路:

用最大堆,每次取完一个堆顶就重新构建一次。用的是以前写堆排序的代码。

题解:

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        # 调整堆
        def adjust_heap(lists, i, size):#以i为根节点开始调整成以i为根节点的最大堆
            lchild = 2 * i + 1#堆是完全二叉树,可求左右子树
            rchild = 2 * i + 2
            max = i
            if i < size / 2:#完全二叉树的分支节点(就是有叶子节点的)小于等了size/2
                if lchild < size and lists[lchild] > lists[max]:
                    max = lchild
                if rchild < size and lists[rchild] > lists[max]:
                    max = rchild
                if max != i:#如果根节点不是最大就调换位置
                    lists[max], lists[i] = lists[i], lists[max]
                    adjust_heap(lists, max, size)#然后以max为根节点进行调整

        # 创建堆
        def build_heap(lists, size):#从下往上构建堆
            for i in range(0, int(size/2))[::-1]:
                adjust_heap(lists, i, size)
        
        size = len(nums)
        build_heap(nums,size)#先创建堆
        count = 0
        for i in range(0, size)[::-1]:#i从size-1到1
            nums[0], nums[i] = nums[i], nums[0]#交换堆顶和堆底
            count += 1 #获得一个最大值加1
            if count == k:
                #print(nums[i])
                return nums[i]
            adjust_heap(nums, 0, i)#把剩下的重新排

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值