最难的部分是抽象出栈这个数据结构
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> stack = new ArrayDeque<>();
int len = asteroids.length;
for (int i = 0; i < len; i++) {
int asteroid = asteroids[i];
if (stack.isEmpty()) {
stack.add(asteroid);
} else {
int top = stack.peek();
if (asteroid > 0 || top < 0 && asteroid < 0) {
stack.push(asteroid);
} else if (Math.abs(asteroid) == Math.abs(top)) {
stack.pop();
} else if (Math.abs(asteroid) > Math.abs(top)) {
i--;
stack.pop();
}
}
}
int size = stack.size();
int[] ans = new int[size];
for (int i = size - 1; i >= 0; i--) {
ans[i] = stack.pop();
}
return ans;
}
}