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

LeetCode 83: Remove Duplicates from Sorted List

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

基本資料
#

難易度: easy 第一次嘗試:2022-07-20

  • 提交紀錄:Runtime Error ×2 → Time Limit Exceeded ×2 → Accepted → Runtime Error → Wrong Answer ×2 → Accepted → Runtime Error ×2 → Accepted ×4 → Runtime Error → Accepted ×2

解題思路
#

已排序的串列重複的值一定相鄰。cur.next 跟 cur 一樣就把它跳過,cur 不動(下一個也可能一樣);不一樣才往前走(Linked List 模板一)。頭節點一定會留下,所以不需要 dummy。

我的嘗試
#

這是我 2022 年 7 月最早寫的幾題之一,18 次提交裡大部分是還不熟悉 ListNode:

  • 一開始用了 self.val、把值和節點拿來比(head.val != head.next),也回傳了 list 而不是節點,RE 和 TLE。
  • 之後空串列時回傳 ListNode(None) 或 ListNode(0),多了一個節點(WA);或沒有檢查 cur.next,[3, 3] 時報錯。

正確解法
#

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur = head
        while cur and cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

複雜度
#

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

要特別避免的錯誤
#

  • 空串列要回傳 None,不是 ListNode(None) 或 ListNode(0)。
  • 比較的是 cur.val 和 cur.next.val,不是值和節點。

面試口說整理
#

串列已排序,重複的值一定相鄰,所以 cur.next 跟 cur 一樣就跳過,不一樣才往前走。時間 O(n)、空間 O(1)。

相關文章

LeetCode 144: Binary Tree Preorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 解題筆記:迭代的前序遍歷,彈出就記錄,先推右小孩再推左小孩,左邊才會先處理
LeetCode 94: Binary Tree Inorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 解題筆記:迭代的中序遍歷,一路往左把節點推進 stack,彈出時記錄,再轉向右子樹
LeetCode 69: Sqrt(x)
·1 分鐘
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 解題筆記:找最大的 mid 讓 mid² <= x;閉區間二分結束時 r 就是答案
LeetCode 27: Remove Element
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 27 解題筆記:寫入指標只寫不等於 val 的數,最後回傳寫入的個數
LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 35: Search Insert Position
·1 分鐘
LeetCode Easy Array Binary-Search
LeetCode 35 解題筆記:找第一個 >= target 的位置(lower bound);半開區間 [l, r) 要配 r = mid,不能寫 r = mid - 1