题目描述
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.
样例
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
算法1
(模拟) $O(n)$
Python 代码
def asteroidCollision(self, asteroids):
res = []
for asteroid in asteroids:
while len(res) and asteroid < 0 and res[-1] > 0:
if res[-1] == -asteroid: #相同则消除
res.pop()
break
# 栈顶小则弹出(正的消除)
elif res[-1] < -asteroid:
res.pop()
continue
# 栈顶大则把负的消除
elif res[-1] > -asteroid:
break
else:
res.append(asteroid) #负的到站底,就可以加入答案了
return res
即三种情况需要处理(相撞):①栈非空 ②当前为负 ③栈顶为正