leetcode 1046. 最后一块石头的重量

6 篇文章 0 订阅
2 篇文章 0 订阅

有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。

 

提示:

1 <= stones.length <= 30
1 <= stones[i] <= 1000

class Solution {

    /**
     * @param Integer[] $stones
     * @return Integer
     */
    function lastStoneWeight($stones) {
        $count = count($stones);
        $half = $count>>1;
        for($i= $half-1;$i>=0;$i--){
            $stones = $this->siftDown($i,$half,$stones);
        }
        while($stones){
            $count =  count($stones);
            if($count == 1){
                return $stones[0];
            }elseif($count == 2){
                return $stones[0]-$stones[1];
            }
            $first = $stones[0];
            $second = $stones[1];
            if($stones[2] >$second){
                $tmp = $stones[2];
                $stones[2] = $second;
                $second = $tmp; 
                $stones = $this->siftDown(2,$count>>1,$stones);
            }
            $diff_value = $first - $second;
            $pop = array_pop($stones);
            $stones[0] = $pop;
            $stones[1] = $diff_value;
            $half = ($count-1)>>1;
            $stones = $this->siftDown(1,$half,$stones);
            $stones = $this->siftDown(0,$half,$stones);
        }
    

        
        
    }
    //大顶堆排序
    function siftDown($index,$half,$arr){
        $element = $arr[$index];
        while($index< $half){
            $ChildIndex = ($index<<1) +1;
            $rChildIndex = $ChildIndex+1;
            if(isset($arr[$rChildIndex]) && $arr[$rChildIndex] >$arr[$ChildIndex]){
                $ChildIndex = $rChildIndex;
            }
            if($element >=$arr[$ChildIndex]){
                break;
            }
            $arr[$index] = $arr[$ChildIndex];
            $index = $ChildIndex;
        }
        $arr[$index] = $element;
        return $arr;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/last-stone-weight
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值