有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
链接:https://leetcode-cn.com/problems/last-stone-weight
思路 :建立大根堆(利用比较器重写优先级队列的规则) ,然后每次依照题目的处理办法对堆顶和堆第二个元素进行处理,
注意:return queue.size()==1 ? queue.peek() : 0;
class Solution {
public int lastStoneWeight(int[] stones) {
if (stones.length==0) return -1;
Queue queue = new PriorityQueue<>(new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for (int i = 0; i < stones.length; i++) {
queue.offer(stones[i]);
}
while (queue.size() > 1){
int tmp = queue.poll();
if (queue.isEmpty()) return tmp;
if (tmp == queue.peek()){
queue.poll();
}else if (tmp > queue.peek()){
queue.offer(tmp-queue.poll());
}
}
return queue.size()==1 ? queue.peek() : 0;
}
}