大根堆解决数组topk元素问题leetcode215

这篇博客介绍了如何用Python实现大根堆,并提供了两种方法:调用heapq库和手写大根堆。作者首先展示了使用heapq库创建大根堆并找到第k大的元素,然后详细解释了如何从头构建大根堆以及调整堆的过程。通过这两个实现,读者可以深入理解大根堆的工作原理和操作技巧。
摘要由CSDN通过智能技术生成

调库大根堆

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        maxHeap = []
        for x in nums:
            heapq.heappush(maxHeap, -x)
        for _ in range(k - 1):
            heapq.heappop(maxHeap)
        return -maxHeap[0]

手写大根堆

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        n = len(nums)
        self.build_maxHeap(nums)
        for i in range(k-1):
            nums[0], nums[n-1-i] = nums[n-1-i], nums[0]
            self.adjust_down(nums, 0, n-1-i-1)
        return nums[0]


    def build_maxHeap(self, nums: List[int]) -> None:
        n = len(nums)
        for root in range(n//2, -1, -1):
            self.adjust_down(nums, root, n - 1)

    def adjust_down(self, nums: List[int], root: int, hi: int) -> None: 
        if root > hi:
            return 
        t = nums[root]
        child = 2 * root + 1
        while child <= hi:
            if child + 1 <= hi and nums[child] < nums[child + 1]:
                child += 1
            if t >= nums[child]:
                break
            nums[root] = nums[child]
            root = child
            child = 2 * root + 1
        nums[root] = t
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值