解题思路
由于我们需要每次将最大的两个石头进行相互销毁,所以每次取出后需要不断的排序。
在这里采用优先队列的方式来解决这个问题。
- 先创建一个优先队列pq,利用最大堆(最大堆就是每次取出的都是队列中所有元素最大的)将所有的元素都放到堆中去。
PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b-a);
其中(a,b) -> b-a是lambda表达式,等价于
new Comparator<Integer>(){public int compare(Integer a,Integer b){return b.compareTo(a);}
- 然后再每次poll出堆中最大的和第二大的元素,然后将二者先减后放到堆中去,不断循环至堆中只有一个元素或者空了为止。
while (pq.size() > 1) {
int a = pq.poll();
int b = pq.poll();
pq.offer(a-b);
}
代码
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b-a);
for (int stone : stones) {
pq.offer(stone);
}
while (pq.size() > 1) {
int a = pq.poll();
int b = pq.poll();
pq.offer(a-b);
}
return pq.isEmpty() ? 0 : pq.poll();
}
}