难度简单41有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
方法一:排序
class Solution {
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
if(stones.length>1){
while(stones[stones.length-2]!=0) {
//只要倒数第二个数不是0,就一直循环
int y=stones[stones.length-1];
int x=stones[stones.length-2];
stones[stones.length-2]=0;
stones[stones.length-1]=y-x;
Arrays.sort(stones);
}
}
return stones[stones.length-1];
}
}
方法二 队列 使用Comparator比较器
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> p=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for (int i = 0; i <stones.length; i++) {
p.offer(stones[i]);
}
while(p.size()>1){
int y=p.poll();
int x=p.poll();
if(y!=x){
p.offer(y-x);
}
}
if(p.isEmpty()){
return 0;
}
return p.peek();
}
}
也可写成 lambda表达式
PriorityQueue<Integer> p=new PriorityQueue<>((a,b)->{
return b-a;
});