Open fockspaces opened 1 year ago
GPT improve:
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
# only collid with [+, -] case
while stack and asteroid < 0 < stack[-1]:
if abs(stack[-1]) < abs(asteroid):
stack.pop()
continue
elif abs(stack[-1]) == abs(asteroid):
stack.pop()
break
else:
stack.append(asteroid)
return stack
continue: 用於繼續執行判斷 break: 用於結束判斷
這邊 break 之所以分開,是因為 break handle 了全部 if 判斷中,沒用 continue 的欄位 如果要寫進去,則需要每個 elif 都 break 一次
老題目,但還沒掌握精髓