- Apr 01 Thu 2021 22:28
-
Leetcode 筆記-reverse string 翻轉字串系列
- Mar 31 Wed 2021 23:59
-
Leetcode 筆記-7. reverse integer (常見面試問題)
- Mar 30 Tue 2021 15:21
-
Leetcode 筆記 - 152. Maximum Product Subarray
- Mar 30 Tue 2021 14:45
-
Leetcode - Kadane's Algorithm 解「最大子數列問題」
- Mar 28 Sun 2021 23:23
-
Leetcode 筆記-238. Product of Array Except Self
- Mar 08 Mon 2021 16:30
-
Hack(?) a website | 台灣總統(小英)變 Elsa?
- Mar 06 Sat 2021 10:27
-
那些你沒看到的細節 Queen's Gambit《后翼棄兵》| 爆紅 Netflix 美劇影評
- Mar 05 Fri 2021 21:26
-
Leetcode 筆記-42. Trapping Rain Water
- Mar 05 Fri 2021 13:00
-
Leetcode 筆記-142. Linked List Cycle II

今天要來解的題目是 Leetcode-142. Linked List Cycle II ,難度為中等,
而我所使用的語言是 python3
壹、理解題目
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.Notice that you should not modify the linked list.
簡單而言,就是
如果有 cycle:回傳 cycle 的起始點
如果沒有:回傳 None
其實這題是 141 的延伸題(如何判斷有沒有 cycle?)
在做這題之前,可以先點進這裡看 141 的解法喔!
同樣會使用到此演算法:Floyd's Tortoise and Hare (Cycle Detection)
貳、開始解題
解決 141 後,你應該就知道如何判斷是否有 cycle 了!
就是龜兔第二次相遇的時候,但
他們第二次相遇的 node 不一定會是 cycle 的起始點 (cycle head),
那麼 要如何找到 cycle head 呢?
在結束第一階段-讓兩者相遇之後,
讓 tortoise 回到原點,而 hare 每次只走一步 (just like tortoise),
直到兩者再次相遇,那個點就會是 cycle head!
Why?
所有的 case 都可以簡化成以下的圖
L 是起始點和 cycle head 的距離、x 是 cycle head 到第一次見面的距離、C 是整個 cycle 的長度
- Mar 04 Thu 2021 13:49
-
Leetcode 筆記-141. Linked List Cycle
- Feb 24 Wed 2021 13:00
-
數學女孩:費馬最後定理 | 科普書籍觀後感
- Feb 23 Tue 2021 13:33
-
爺爺的證明題:上帝存在嗎? | 科普書籍觀後感








