LeetCode刷题笔记第1046题:最后一块石头的重量

LeetCode刷题笔记第1046题:最后一块石头的重量

想法:
通过给定的数据元素构建大顶堆,并根据题中所给限制完成最后一块石头的重量(如果存在最后一块石头)。

class Solution:
    def lastStoneWeight(self, stones) :
        def sift_down(stones, parent):
            val = stones[parent]
            while parent <<1 <len(stones):
                child = parent << 1
                if child|1 < len(stones) and stones[child] <stones[child|1]:
                    child = child | 1
                if val< stones[child]:
                    stones[parent] = stones[child]
                    parent = child
                else:
                    break
            stones[parent] = val


        #最大堆
        stones.insert(0,'dummy')
        # print(stones)
        # print(len(stones))
        parent = (len(stones)-1)>>1
        for i in range(parent,0,-1):
            sift_down(stones,i)
        while len(stones)>2:
            stone1 = stones[1]
            stones[1]=stones.pop(-1)
            sift_down(stones,1)
            stone2 = stones[1]
            #此时stones里除了占位符,至少还有一块石头。
            if stone2 == stone1:
                if len(stones) >2:
                    stones[1] = stones.pop(-1)
                    sift_down(stones,1)
                else:
                    stones.pop(-1)
                        
            else:
                stones[1] = stone1 - stone2
                sift_down(stones,1)
        stones.pop(0)
        if stones == []:
            return 0
        else:
            return stones[0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值