优先队列
import java.util.Collections;
import java.util.PriorityQueue;
class Solution {
public int lastStoneWeight(int[] stones) {
/**
* 使用优先队列创建最大堆
* Collections.reverseOrder()比较器可以反转默认的最小堆
*/
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < stones.length; i++) {
pq.add(stones[i]);
}
while (pq.size() > 1){
int y = pq.poll();
int x = pq.poll();
if (x != y) {
pq.add(y - x);
}
}
return pq.size() == 1 ? pq.poll() : 0;
}
}
/**
* 时间复杂度 O(nlogn)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/last-stone-weight/