LeetCode75-735-Asteroid-Collision

🧠 思路总结

只有在一种情况下才会发生碰撞:左边的往右(+),右边的往左(-)。后面新的元素要和前面(最后)的元素进行反复比较,所以使用Stack。

❗ 易错点 / 小坑

  • 注意最后要翻转stack

✅ 代码(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
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int x : asteroids) {
boolean alive = true;
while (alive && x < 0 && !stack.isEmpty() && stack.peek() > 0) {
int top = stack.peek();
if (Math.abs(top) < Math.abs(x)) {
stack.pop();
} else if (Math.abs(top) == Math.abs(x)) {
stack.pop();
alive = false;
} else {
alive = false;
}
}
if (alive) {
stack.push(x);
}
}
int[] res = new int[stack.size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = stack.pop();
}
return res;
}
}

LeetCode75-735-Asteroid-Collision
https://powersixxx.github.io/leetcode-blog/2026/02/07/LeetCode75-735-Asteroid-Collision/
作者
Baowen Liu
发布于
2026年2月7日
许可协议