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

LeetCode 876: Middle of the Linked List

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

基本資料
#

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

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

解題思路
#

快指針的速度是慢指針的兩倍,快的走完時慢的剛好走一半(Linked List 模板三)。條件用 while fast and fast.next:偶數長度時會多走一步,slow 停在兩個中點的第二個,剛好是題目要的。

我的嘗試
#

第一次寫時先把值存進 list 再取中間,index 算錯了幾次(偶數長度用了 / 得到浮點數,奇數長度又多加了 1),而且回傳的是值、不是節點。之後改寫成兩個指標時:

  • 一版迴圈裡沒有移動 node,還直接取 node.next.next,[3] 時報錯。
  • 一版先更新 middle = node.next 再走兩步,多走了一格,[7, 1, 7, 2] 回傳 [2],答案是 [7, 2]。

正確解法
#

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        return slow

複雜度
#

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

要特別避免的錯誤
#

  • 偶數長度要停在第二個中點,迴圈條件決定停在哪一個。

面試口說整理
#

快指針一次兩步、慢指針一次一步,快的走到底時慢的就在中間;用 fast and fast.next 當條件,偶數長度時剛好停在第二個中點。時間 O(n)。

相關文章

LeetCode 234: Palindrome Linked List
·1 分鐘
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 解題筆記:快慢指針找中點,反轉後半段,再從兩端往中間比;O(1) 額外空間
LeetCode 141: Linked List Cycle
·1 分鐘
LeetCode Easy Hash-Table Linked-List Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 141 解題筆記:Floyd 判圈,快指針一次兩步、慢指針一次一步,有環就一定會相遇;兩個都要從自己的位置往前走
LeetCode 160: Intersection of Two Linked Lists
·1 分鐘
LeetCode Easy Hash-Table Linked-List Two-Pointers
LeetCode 160 解題筆記:兩個指標走完自己的串列就換走對方的,都走 lenA + lenB 步,會同時到達交點或同時到 None
LeetCode 821: Shortest Distance to a Character
·1 分鐘
LeetCode Easy Array Two-Pointers String
LeetCode 821 解題筆記:左往右掃一次記錄到左邊最近的 c 的距離,右往左再掃一次取較小值
LeetCode 832: Flipping an Image
·1 分鐘
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 解題筆記:每一列先左右反轉再把 0、1 互換;可以用左右指針同時做
LeetCode 844: Backspace String Compare
·1 分鐘
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 解題筆記:用 stack 模擬退格;O(1) 空間的話從尾巴往前,遇到 # 就記下要跳過幾個字元