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

LeetCode 82: Remove Duplicates from Sorted List II

·1 分鐘· ·
LeetCode Medium Linked-List Two-Pointers
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-10-26

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

解題思路
#

跟 LC 83 不同,重複的值一個都不留,頭也可能被刪,所以用 dummy(Linked List 模板一):

  • prev 是最後一個確定留下來的節點。
  • cur = prev.next。如果 cur 跟下一個一樣,就一路往後跳過所有同樣的值,再讓 prev.next 指向第一個不同的節點(prev 不動,那個節點還要再檢查)。
  • 沒有重複就 prev 往前走。

我的嘗試
#

2022 年提交了 16 次:

  • 前幾版沒有 dummy、沒有處理空串列,[] 時取 None.next 報錯;有一版連回傳值都沒寫。
  • 加了 dummy 之後,一版最後回傳 prev.next:prev 已經往後移了,回傳的不是頭。例如 [1, 2]:答案 [1, 2],回傳 [2]。
  • 一版內層 while 沒檢查 cur.next,[1, 1] 時報錯。

正確解法
#

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = prev = ListNode(0, head)
        while prev.next:
            cur = prev.next
            if cur.next and cur.val == cur.next.val:
                while cur.next and cur.val == cur.next.val:
                    cur = cur.next
                prev.next = cur.next                 # 整段重複的都跳過
            else:
                prev = prev.next
        return dummy.next

複雜度
#

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

要特別避免的錯誤
#

  • 跳過重複之後 prev 不要前進,新的 prev.next 也可能是重複的。
  • 回傳 dummy.next,不是 prev.next。

面試口說整理
#

重複的全部刪,頭也可能被刪,所以我用 dummy,prev 是最後確定保留的節點。看到重複就跳到下一個不同的值,讓 prev.next 直接接過去;沒有重複才讓 prev 前進。時間 O(n)。

相關文章

LeetCode 86: Partition List
·1 分鐘
LeetCode Medium Linked-List Two-Pointers
LeetCode 86 解題筆記:兩個 dummy 分別接小於 x 和大於等於 x 的節點,最後接起來,第二段的尾巴設成 None
LeetCode 19: Remove Nth Node From End of List
·1 分鐘
LeetCode Medium Linked-List Two-Pointers
LeetCode 19 解題筆記:從 dummy 出發,快指針先走 n + 1 步,再一起走到底,慢指針停在要刪的前一個
LeetCode 61: Rotate List
·1 分鐘
LeetCode Medium Linked-List Two-Pointers
LeetCode 61 解題筆記:先算長度並接成環,k %= n,從頭走 n - k - 1 步找到新的尾巴再斷開
LeetCode 75: Sort Colors
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 解題筆記:荷蘭國旗:low 左邊都是 0、high 右邊都是 2;遇到 2 換到 high 之後不要前進,換過來的數還沒檢查
LeetCode 80: Remove Duplicates from Sorted Array II
·1 分鐘
LeetCode Medium Array Two-Pointers
LeetCode 80 解題筆記:每個值最多留兩個:跟寫入位置往前第二個 nums[k - 2] 比,不一樣才寫
LeetCode 24: Swap Nodes in Pairs
·1 分鐘
LeetCode Medium Linked-List Recursion
LeetCode 24 解題筆記:dummy 加上兩兩一組,prev.next、a.next、b.next 三個指標一起重接;交換的是節點不是值