Asteroid Collision
Problem statement
You are given an integer array asteroids. Each value is one asteroid, and the array lists them in a row from left to right.
The absolute value of a number is the asteroid's size. The sign is its direction: a positive value moves right and a negative value moves left. All asteroids move at the same speed.
Two asteroids collide only when the one on the left moves right and the one on the right moves left. When they collide, the smaller one explodes. If they have the same size, both explode. The surviving asteroid keeps moving and can collide again. Asteroids that move in the same direction, or away from each other, never meet.
Return the asteroids that are left after all collisions, in their original left-to-right order.
Function
asteroidCollision(asteroids: int[]) → int[]Examples
Example 1
asteroids = [4,7,-3]return = [4,7]The -3 moves left and meets 7, which moves right. 7 is larger, so -3 explodes.
The 4 and the 7 both move right, so they never meet. The answer is [4,7].
Example 2
asteroids = [6,-6]return = []The 6 moves right and the -6 moves left, so they meet. They have the same size, so both explode and nothing is left.
Example 3
asteroids = [-2,-1,3,1,-4,2]return = [-2,-1,-4,2]The -2 and -1 both move left, and nothing to their left moves right, so they never collide.
The -4 first meets 1 and destroys it, then meets 3 and destroys it. After that, the next asteroid on its left is -1, which moves the same way, so -4 survives.
The last 2 moves right, away from everything. The answer is [-2,-1,-4,2].
Constraints
2 <= asteroids.length <= 10^4-1000 <= asteroids[i] <= 1000asteroids[i] != 0