ZhongKuo0228 / study

0 stars 0 forks source link

735. Asteroid Collision #83

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

老題目,但還沒掌握精髓

  1. stack 來做連續比較
  2. 當 stack top 為正,才需處理接下來發生的事
  3. 列出條件,一個個處理
class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        stack = []
        for asteroid in asteroids:
            explode = False
            while stack and stack[-1] > 0:
                result = asteroid + stack[-1]
                if result > 0:
                    explode = True if asteroid < 0 else False
                    break
                elif result == 0:
                    stack.pop()
                    explode = True
                    break
                else:
                    stack.pop()
            if not explode:
                stack.append(asteroid)

        return stack

# 1. cur > ast: pass
# 2. cur == ast: pop and pass
# 3. cur < ast: pop     
fockspaces commented 1 year ago

GPT improve:

  1. 用 while...else 來簡化判斷(避免掉 flag)
  2. 巧妙用 continue 和 break 來分化 while 邏輯
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
fockspaces commented 1 year ago

continue: 用於繼續執行判斷 break: 用於結束判斷

這邊 break 之所以分開,是因為 break handle 了全部 if 判斷中,沒用 continue 的欄位 如果要寫進去,則需要每個 elif 都 break 一次