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

LeetCode 86: Partition List

·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

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

解題思路
#

要保持原本的相對順序,所以照順序掃一次,小於 x 的接到第一個 dummy 後面、其他接到第二個 dummy 後面(Linked List 模板一)。最後第一段的尾巴接上第二段的頭,第二段的尾巴要設成 None,不然可能還連著原本串列的節點,形成環。

我的嘗試
#

第一版直接移動 dummy 本身當尾巴,最後回傳 l1.next 時已經不是頭,[1]、x = 2 回傳空的。之後重寫時一版用了沒定義的變數 target,一版沒處理全部都在同一段的情況(空串列時報錯)。

正確解法
#

class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        small = s = ListNode()
        big = b = ListNode()
        while head:
            if head.val < x:
                s.next = s = head
            else:
                b.next = b = head
            head = head.next
        b.next = None
        s.next = big.next
        return small.next

複雜度
#

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

要特別避免的錯誤
#

  • dummy 和移動的尾巴指標要分開。
  • 第二段的尾巴設成 None。

面試口說整理
#

我用兩個 dummy,依序把小於 x 的節點接到第一條、其他接到第二條,最後兩條接起來並把結尾設成 None。原本的順序保留了。時間 O(n)。

相關文章

LeetCode 82: Remove Duplicates from Sorted List II
·1 分鐘
LeetCode Medium Linked-List Two-Pointers
LeetCode 82 解題筆記:重複的值要全部刪掉,頭也可能被刪,所以用 dummy;發現重複就一路跳到不同的值,再讓 prev.next 接過去
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 三個指標一起重接;交換的是節點不是值