#735
Asteroid Collision
specialist · 920 · lc medium +32 · verified · 47.2% accepted · 9,292 likes · top 32%
Description
You are given an integer array asteroids where each element's absolute value is its size and its sign is its direction: positive means moving right, negative means moving left. All asteroids travel at the same speed.
When a right-moving asteroid meets a left-moving one, the smaller explodes; equal-sized ones both explode. Asteroids moving in the same direction never collide. Return the array state after all collisions have resolved.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input: asteroids = [3,5,-6,2,-1,4]
Output: [-6,2,4]
Explanation: The asteroid -6 makes the asteroid 3 and 5 explode, and then continues going left. On the other side, the asteroid 2 makes the asteroid -1 explode and then continues going right, without reaching asteroid 4.
Code
1
2
3