↓快轉到主要內容
  1. LeetCode/

LeetCode 735: Asteroid Collision

·1 分鐘· ·
LeetCode Medium Array Stack Simulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2024-04-18

  • 提交紀錄:Wrong Answer → Runtime Error → Wrong Answer → Output Limit Exceeded → Accepted

解題思路
#

從左到右(Stack 模板二),只有 stack 頂端往右(> 0)、目前的往左(< 0)時會相撞:

  • 頂端比較小:頂端爆掉,繼續跟新的頂端比。
  • 一樣大:兩個都爆。
  • 頂端比較大:目前的爆掉。

目前的沒爆就 push。往左的遇到空 stack 或往左的頂端,都不會相撞。

我的嘗試
#

2024 年寫的時候是從右往左掃,用另一個 stack 存往左的:

  • 第一版最後沒有把剩下的往左的小行星加回答案:[-4, 2] 回傳 [2]。
  • 補上之後,比較的對象用了 rev_stack[0](最遠的那顆),應該跟最近的 rev_stack[-1] 比:[2, -4, -1] 回傳 [-4],答案 [-4, -1]。改成 [-1] 才 AC,中間還有一次 print 造成 Output Limit Exceeded。

正確解法
#

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        st = []
        for a in asteroids:
            alive = True
            while alive and a < 0 and st and st[-1] > 0:
                if st[-1] < -a:
                    st.pop()
                elif st[-1] == -a:
                    st.pop()
                    alive = False
                else:
                    alive = False
            if alive:
                st.append(a)
        return st

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 只有右邊往左、左邊往右才會相撞;[-4, 2] 不會相撞。
  • 要跟最近的那一顆比,是 stack 的頂端 st[-1],不是 st[0]。

面試口說整理
#

我從左到右用 stack,只有頂端往右、目前的往左時才會相撞,頂端比較小就爆掉繼續比,一樣大一起爆,比較大就把目前的擋掉;沒爆的放進 stack。每顆最多進出一次,時間 O(n)。

相關文章

LeetCode 54: Spiral Matrix
·1 分鐘
LeetCode Medium Array Matrix Simulation
LeetCode 54 解題筆記:維護上下左右四個邊界,依序走右、下、左、上,每走完一邊就把那個邊界往內縮
LeetCode 59: Spiral Matrix II
·1 分鐘
LeetCode Medium Array Matrix Simulation
LeetCode 59 解題筆記:跟 LC 54 一樣維護四個邊界,只是把讀取換成依序填入 1 到 n²
LeetCode 682: Baseball Game
·1 分鐘
LeetCode Easy Array Stack Simulation
LeetCode 682 解題筆記:用 stack 存有效的分數,C 刪掉最後一個,D 加入兩倍,+ 加入最後兩個的和
LeetCode 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模
LeetCode 3075: Maximize Happiness of Selected Children
·1 分鐘
LeetCode Medium Array Greedy Sorting
LeetCode 3075 解題筆記:由大到小選 k 個,第 i 個選的會被扣 i,扣到 0 為止
LeetCode 3070: Count Submatrices with Top-Left Element and Sum Less Than k
·1 分鐘
LeetCode Medium Array Matrix Prefix-Sum
LeetCode 3070 解題筆記:包含左上角的子矩陣就是二維前綴和 P[i][j],數有幾個 <= k