题目:
思路:
- 利用优先级队列求解,
- 因为优先级队列默认升序排序,所以要先重写比较方法.
- 因为每次拿的都是最重的两块石头,就相当于取优先级队列的队首两个元素进行比较操作.在比较过程中有可能会产生新的较轻的石头,所以通过使用优先级队列可以减少每次的比较操作.
- 注意compare方法里的写法
代码:
//最后一块石头的重量.使用优先级队列来做
public int lastStoneWeight(int[] stones) {
//优先级队列默认升序,所以需要重写compare方法
Queue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
//要降序,所以o2 - o1
return o2 - o1;
}
});
//遍历数组,将数组元素入队列
for (int i= 0;i < stones.length;i++){
queue.offer(stones[i]);
}
//模拟比较过程,当队列中只剩一个元素或0个元素时结束比较
while (queue.size()>1){
int t1 = queue.poll();//第一大的数
int t2 = queue.poll();//第二大的数
if (t1 == t2){
//t1和t2都不要了,继续查找下两个队首
continue;
}
else {
//将他两的差值重新入队列,基于优先级队列的排序性,会重新进行降序排序
int diff = Math.abs(t1 - t2);
queue.offer(diff);
}
}
return queue.isEmpty()? 0:queue.poll();
}