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

LeetCode 141: Linked List Cycle

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

基本資料
#

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

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

解題思路
#

有環的話,進入環之後快指針每一步都比慢指針多拉近 1 格,一定會追上;沒有環的話快指針會先走到 None(Linked List 模板三)。

我的嘗試
#

這題 2022 年提交了 19 次:

  • TLE:寫成 slow = head.next、fast = head.next.next,每次都從 head 重算,兩個指標永遠停在同一個地方。例如 [3, 3] 成環時一直跑不完。
  • RE:空串列或沒有環時取了 None.next,例如 [] 和 [3, 3, 5]。
  • 把條件改成 while fast and fast.next、指標從自己的位置往前走就 AC 了。

正確解法
#

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow is fast:
                return True
        return False

複雜度
#

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

要特別避免的錯誤
#

  • 每一步是 slow.next、fast.next.next,不是從 head 重新算。
  • 空串列和只有一個節點時,while 條件直接擋掉。

面試口說整理
#

我用快慢指針,快的一次兩步、慢的一次一步。有環的話快的一定會在環裡追上慢的;快的走到 None 就代表沒有環。時間 O(n)、空間 O(1)。

相關文章

LeetCode 160: Intersection of Two Linked Lists
·1 分鐘
LeetCode Easy Hash-Table Linked-List Two-Pointers
LeetCode 160 解題筆記:兩個指標走完自己的串列就換走對方的,都走 lenA + lenB 步,會同時到達交點或同時到 None
LeetCode 169: Majority Element
·1 分鐘
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 解題筆記:Boyer-Moore 投票,不同的數兩兩抵消,最後留下的就是出現超過一半的那個
LeetCode 125: Valid Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 125 解題筆記:左右指針跳過非英數字元,再比較小寫是否相同;數字也要算進去
LeetCode 83: Remove Duplicates from Sorted List
·1 分鐘
LeetCode Easy Linked-List
LeetCode 83 解題筆記:已排序,重複的一定相鄰;cur 跟 cur.next 一樣就跳過 cur.next,不一樣才前進
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 找不到會丟例外