更新了一下写法,这样写不会爆int
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b) -> b > a?1:-1);
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b) -> b - a);
for(int stone : stones){
pq.offer(stone);
}
while(pq.size() > 1){
int a = pq.poll();
int b = pq.poll();
if(a != b){
pq.offer(a - b);
}
}
return pq.isEmpty()? 0 : pq.poll();
}
}
这个写法是用了lam表达式的Compareto函数
- b - a也就是后面的减去前面的说明的降序。

本文介绍了一种改进的算法,利用Java的PriorityQueue和Lambda表达式重排石头,求解最后剩余石头的最小重量。通过(b - a)实现降序比较,简化了代码并提高了效率。
660

被折叠的 条评论
为什么被折叠?



