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
| class Solution { public int[] asteroidCollision(int[] asteroids) { Stack<Integer> stack = new Stack<>(); for (int asteroid : asteroids) { boolean bump = false; while (asteroid < 0 && !stack.isEmpty() && stack.peek() > 0) { if (-asteroid == stack.peek()) { bump = true; stack.pop(); break; } else { if (-asteroid < stack.peek()) { bump = true; break; } else { stack.pop(); } } }
if (!bump) { stack.push(asteroid); } }
int[] res = new int[stack.size()]; for (int i = 0; i < res.length; i++) { res[res.length - 1 - i] = stack.pop(); } return res; } }
|
References
735. Asteroid Collision
剑指 Offer II 037. 小行星碰撞