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

LeetCode 1046: Last Stone Weight

·1 分鐘· ·
LeetCode Easy Array Heap-Priority-Queue
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-30

  • 提交紀錄:Wrong Answer → Runtime Error → Accepted → Runtime Error → Wrong Answer → Accepted → Runtime Error → Accepted ×2

解題思路
#

每次都要最重的兩顆,用 max-heap(Heap,Python 存負數)。拿出 y >= x,不相等就放回 y - x。存的是負數時,-a、-b 拿出來後差的正負號要注意:a - b(兩個負數相減,較重的先出來)會是負的,剛好就是要放回去的負數。最後 heap 空了回傳 0。

我的嘗試
#

這題寫了四次(2022-09、2022-11 兩次、2025),錯了 5 次:

  • 2022-09 第一版放回 x - y,存的是負數,這個差是正的,被當成很輕的石頭:[2, 7] 回傳 -5,答案 5。改成 y - x 之後,兩顆一樣重全部消掉時 h[0] 超出範圍(IndexError)。
  • 2022-11 重寫時,條件寫反成 if heaviest != second_heaviest: continue,不一樣重的反而直接丟掉:[2, 7] 回傳 0。另外兩次是 heap 空了的 IndexError。

正確解法
#

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        h = [-s for s in stones]
        heapq.heapify(h)
        while len(h) > 1:
            a = heapq.heappop(h)
            b = heapq.heappop(h)
            if a != b:
                heapq.heappush(h, a - b)
        return -h[0] if h else 0

複雜度
#

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

要特別避免的錯誤
#

  • 存負數時差的正負號要對:放回去的也要是負數。
  • 最後可能一顆都不剩,要回傳 0。

面試口說整理
#

每次都要最重的兩顆,我用存負數的 max-heap,拿出兩顆,不一樣重就把差放回去,最後剩一顆就回傳它,沒有就回傳 0。時間 O(n log n)。

相關文章

LeetCode 506: Relative Ranks
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 解題筆記:把 index 按分數由高到低排序,前三名給獎牌,其他給名次的字串,放回原本的位置
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 分鐘
LeetCode Easy Array Greedy Sorting
LeetCode 1005 解題筆記:每次把最小的數變號;最小的已經是正數時,剩下的次數只要看奇偶
LeetCode 1013: Partition Array Into Three Parts With Equal Sum
·1 分鐘
LeetCode Easy Array Greedy
LeetCode 1013 解題筆記:總和要能被 3 整除,從左邊累加,每湊到 total / 3 就切一刀,切出至少 3 段就成立
LeetCode 1018: Binary Prefix Divisible By 5
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 1018 解題筆記:前綴每多一位就是 x = 2x + bit,只要保留 x mod 5,數字不會變大