有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。