-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStoneWeightResolver.java
46 lines (40 loc) · 1.3 KB
/
StoneWeightResolver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package org.sean.array;
import java.util.Comparator;
import java.util.PriorityQueue;
/** * 1046. Last Stone Weight */
public class StoneWeightResolver {
private PriorityQueue<Integer> priorityQueue;
public int lastStoneWeight(int[] stones) {
if (stones == null || stones.length == 0) return 0;
if (stones.length == 1) {
return stones[0];
}
int size = stones.length;
priorityQueue =
new PriorityQueue<>(
size,
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
for (int i : stones) {
priorityQueue.add(i);
}
while (!priorityQueue.isEmpty()) {
Integer elem = priorityQueue.poll();
if (elem != null) {
Integer next = priorityQueue.poll();
if (next != null) {
if (!elem.equals(next)) {
priorityQueue.add(elem - next);
}
} else {
return elem;
}
}
}
return 0;
}
}