思路
思路没啥可说的,评论区看到一个有意思的方法,不取出最大的两个,将其变为0来代替取出,结束条件变为倒数第三个数为0.
还有一个是优先队列使用最大堆,记录一下提醒自己别忘了PriorityQueue(优先队列)。
代码代码一
class Solution {
public int lastStoneWeight(int[] stones) {
if(stones.length == 2)
return Math.abs(stones[0]-stones[1]);
if(stones.length == 1)
return stones[0];
Arrays.sort(stones);
if(stones[stones.length-3] == 0)
return stones[stones.length - 1] - stones[stones.length - 2];
stones[stones.length-1] = stones[stones.length-1] - stones[stones.length-2];
stones[stones.length-2] = 0;
return lastStoneWeight(stones);
}
}
代码二
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue q = new PriorityQueue((a, b) -> b-a);
for(int stone : stones){
q.offer(stone);
}
while(q.size() > 1){
int a = q.poll();
int b = q.poll();
q.offer(a - b);
}
return q.isEmpty()?0:q.poll();
}
}



