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
| class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int asteroid : asteroids) {
if (asteroid > 0) {
stack.push(asteroid);
} else {
while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() + asteroid < 0) {
stack.pop();
}
if (stack.isEmpty() || stack.peek() < 0) {
stack.push(asteroid);
} else if (stack.peek() + asteroid == 0) {
stack.pop();
}
}
}
int[] res = new int[stack.size()];
int index = stack.size() - 1;
while (!stack.isEmpty()) {
res[index--] = stack.pop();
}
return res;
}
}
|