🧠 思路总结
只有在一种情况下才会发生碰撞:左边的往右(+),右边的往左(-)。后面新的元素要和前面(最后)的元素进行反复比较,所以使用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; } }
|