735.Asteroid Collision
Problem description:
We are given an array asteroids
of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
1 | Input: asteroids = [5,10,-5] |
Example 2:
1 | Input: asteroids = [8,-8] |
Example 3:
1 | Input: asteroids = [10,2,-5] |
Example 4:
1 | Input: asteroids = [-2,-1,1,2] |
Constraints:
2 <= asteroids.length <= 104
1000 <= asteroids[i] <= 1000
asteroids[i] != 0
Solution:
If the stack still contains element and stack[-1]
moving toward right but asteroid
moving toward left, check which stays.
else:
some senario
- same direction
- asteroid is negative moving toward left, but no positive in the stack
we just append asteroid
to stack
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: