解法一:大根堆

维护一个大根堆即可。每次取出两个重量最大的石头模拟题目所述操作。

  1. import java.util.PriorityQueue;
  2. class Solution {
  3. public int lastStoneWeight(int[] stones) {
  4. PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2 - o1);
  5. for (int i : stones) {
  6. queue.offer(i);
  7. }
  8. int w1, w2;
  9. while (queue.size() >= 2) {
  10. w1 = queue.poll();
  11. w2 = queue.poll();
  12. if (w1 > w2) {
  13. queue.offer(w1 - w2);
  14. }
  15. }
  16. if (queue.isEmpty()) {
  17. return 0;
  18. } else {
  19. return queue.poll();
  20. }
  21. }
  22. }