class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
main idea: loop through each asteroid and compare it with stack top. discuss especilaly when stack top is positive and current asteroid is negtive
tricky part: if stack top is positive and current asteroid is neg, and abs(top) < abs(cur), stack pop off top asteroid, current asteroid will need to compare with next stack top until top pop condition not exist.
"""
# time O(N) space O(N)
st = []
for a in asteroids:
# case1: top is -, a > 0; case2: top + a - ; case 3: top + a+ or top - a-
while st and a<0<st[-1] :
#case 1 abs(a) > top ; case2 abs(a) < top ;case3: abs(a) == top
if abs(st[-1]) == abs(a):
st.pop()
elif abs(st[-1]) < abs(a):
st.pop()
continue
break
else:
st.append(a)
return st
syntax knowledge for python: while else loop