Skip to main content

Command Palette

Search for a command to run...

LeetCode Solution, Medium, 142. Linked List Cycle II

找出連結序列的迴圈連接節點

Published

I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

142. Linked List Cycle II

題目敘述

Given the head of 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 (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Example 1:

circularlinkedlist.png

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

circularlinkedlist_test2.png

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

circularlinkedlist_test3.png

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 10**4].
  • -10**5 <= Node.val <= 10**5
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

題目翻譯

嘗試在空間複雜度是常數的情況下解題。

這題是昨天 141 的延伸,有一個連接序列 head,要找出迴圈開始的節點。如果沒有迴圈就回傳 null

解法解析

解法也是跟昨天的 141 一樣,使用 Hash Table 或是判圈演算法。不同的是因為要找出的是迴圈的連接點,所以在找到龜兔的交會點時,會需要再從交會點和起始點,重新做一次同速比較來找出迴圈的連接點。詳細的解法概念,應該會再另外寫在演算法系列吧。

解法範例

Go

Hash Table
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    var visited = make(map[*ListNode]bool)

    node := head
    for node != nil {
        if visited[node] {
            return node
        }
        visited[node] = true
        node = node.Next
    }
    return nil
}
Floyd's Tortoise and Hare
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }
    intersect := getIntersect(head)
    if intersect == nil {
        return nil
    }

    ptr1 := head
    ptr2 := intersect
    for ptr1 != ptr2 {
        ptr1 = ptr1.Next
        ptr2 = ptr2.Next
    }
    return ptr1
}

func getIntersect(head *ListNode) *ListNode {
    tortoise := head
    hare := head

    for hare != nil && hare.Next != nil {
        tortoise = tortoise.Next
        hare = hare.Next.Next

        if hare == tortoise {
            return tortoise
        }
    }
    return nil
}

JavaScript

Hash Table
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function (head) {
    const visited = new Set();

    let node = head;
    while (node !== null) {
        if (visited.has(node)) {
            return node;
        }
        visited.add(node);
        node = node.next;
    }
    return null;
};
Floyd's Tortoise and Hare
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function (head) {
    if (head === null) return null;
    const intersection = getIntersection(head);
    if (intersection === null) return null;
    let ptr1 = head,
        ptr2 = intersection;
    while (ptr1 !== ptr2) {
        ptr2 = ptr2.next;
        ptr1 = ptr1.next;
    }
    return ptr1;
};

const getIntersection = (head) => {
    let tortoise = head,
        hare = head;

    while (hare !== null && hare.next !== null) {
        tortoise = tortoise.next;
        hare = hare.next.next;

        if (tortoise === hare) return tortoise;
    }
    return null;
};

Kotlin

Hash Table
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */

class Solution {
    fun detectCycle(head: ListNode?): ListNode? {
        val visited = mutableSetOf<ListNode>()

        var node = head
        while (node != null) {
            if (visited.contains(node)) {
                return node
            }
            visited.add(node)
            node = node.next
        }
        return null
    }
}
Floyd's Tortoise and Hare
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */

class Solution {
    private fun getIntersect(head: ListNode): ListNode? {
        var tortoise: ListNode? = head
        var hare: ListNode? = head

        // A fast pointer will either loop around a cycle and meet the slow
        // pointer or reach the `null` at the end of a non-cyclic list.
        while (hare != null && hare.next != null) {
            tortoise = tortoise?.next
            hare = hare?.next?.next
            if (tortoise === hare) {
                return tortoise
            }
        }
        return null
    }

    fun detectCycle(head: ListNode?): ListNode? {
        if (head == null) {
            return null
        }

        // If there is a cycle, the fast/slow pointers will intersect at some
        // node. Otherwise, there is no cycle, so we cannot find an entrance to
        // a cycle.
        val intersect: ListNode = getIntersect(head) ?: return null

        // To find the entrance to the cycle, we have two pointers traverse at
        // the same speed -- one from the front of the list, and the other from
        // the point of intersection.
        var ptr1: ListNode = head
        var ptr2: ListNode = intersect
        while (ptr1 !== ptr2) {
            ptr1 = ptr1.next
            ptr2 = ptr2.next
        }
        return ptr1
    }
}

PHP

Hash Table
/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */

class Solution
{
    /**
     * @param ListNode $head
     * @return ListNode
     */
    function detectCycle($head)
    {
        $visited = [];
        while (!is_null($head)) {
            if (isset($visited[$head->val])) {
                return $head;
            }
            $visited[$head->val] = true;
            $head = $head->next;
        }
        return null;
    }
}
Floyd's Tortoise and Hare
/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */

class Solution
{
    /**
     * @param ListNode $head
     * @return ListNode
     */
    function detectCycle($head)
    {
        if (is_null($head)) {
            return null;
        }

        $intersect = $this->getIntersect($head);
        if (is_null($intersect)) {
            return null;
        }

        $ptr1 = $head;
        $ptr2 = $intersect;
        while ($ptr1 !== $ptr2) {
            $ptr1 = $ptr1->next;
            $ptr2 = $ptr2->next;
        }
        return $ptr1;
    }

    private function getIntersect($head)
    {
        $tortoise = $head;
        $hare = $head;

        while (!is_null($hare) && !is_null($hare->next)) {
            $tortoise = $tortoise->next;
            $hare = $hare->next->next;
            if ($tortoise === $hare) {
                return $tortoise;
            }
        }
        return null;
    }
}

Python

Hash Table
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def detectCycle(self, head: ListNode | None) -> ListNode | None:
        visited = set()

        node = head
        while node is not None:
            if node in visited:
                return node
            visited.add(node)
            node = node.next

        return None
Floyd's Tortoise and Hare
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def getIntersect(self, head: ListNode | None) -> ListNode | None:
        tortoise = head
        hare = head

        # A fast pointer will either loop around a cycle and meet the slow
        # pointer or reach the `null` at the end of a non-cyclic list.
        while hare is not None and hare.next is not None:
            tortoise = tortoise.next
            hare = hare.next.next
            if tortoise == hare:
                return tortoise

        return None

    def detectCycle(self, head: ListNode | None) -> ListNode | None:
        if head is None:
            return None

        # If there is a cycle, the fast/slow pointers will intersect at some
        # node. Otherwise, there is no cycle, so we cannot find an entrance to
        # a cycle.
        intersect = self.getIntersect(head)
        if intersect is None:
            return None

        # To find the entrance to the cycle, we have two pointers traverse at
        # the same speed -- one from the front of the list, and the other from
        # the point of intersection.
        ptr1 = head
        ptr2 = intersect
        while ptr1 != ptr2:
            ptr1 = ptr1.next
            ptr2 = ptr2.next

        return ptr1

Rust


Swift

Hash Table
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {
    func detectCycle(_ head: ListNode?) -> ListNode? {
        var visited = [ListNode]()

        var node = head
        while node != nil {
            if visited.contains(where: {$0 === node!}) {
                return node
            }
            visited.append(node!)
            node = node?.next
        }
        return nil
    }
}
Floyd's Tortoise and Hare
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {
    private func getIntersect(_ head: ListNode?) -> ListNode? {
        var hare = head, tortoise = head
        while hare != nil, hare?.next != nil {
            tortoise = tortoise?.next
            hare = hare?.next?.next
            if tortoise === hare {
                return tortoise
            }
        }
        return nil
    }

    func detectCycle(_ head: ListNode?) -> ListNode? {
        if head == nil {
            return nil
        }

        let intersect = getIntersect(head)
        if intersect == nil {
            return nil
        }

        var ptr1 = head
        var ptr2 = intersect
        while ptr1 !== ptr2 {
            ptr1 = ptr1?.next
            ptr2 = ptr2?.next
        }
        return ptr1
    }
}

Reference

More from this blog

如何開始入門軟體工程領域 - 名詞解釋(長期更新)

現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...

May 10, 2023

我的 MacBook Pro (Apple Silicon) 設定

現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...

Apr 25, 2023

ChatGPT 下的發展預想

從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...

Mar 23, 2023

不工程的攻城獅

223 posts

I am not a programmer because I am not good at programming. But I do programming. Love to learn new things. An animal lover and a dancer. My oshi is 潤羽るしあ.