142 Linked List Cycle II

25 年 6 月 24 日 星期二
175 字
1 分钟

Solution: https://leetcode.cn/problems/linked-list-cycle-ii/solutions/1999271/mei-xiang-ming-bai-yi-ge-shi-pin-jiang-t-nvsq

the length of cycle: b + c
the distance that slow pointer moved: a + b
the distance that fast pointer moved: a + b + k(b + c)

142_1The distance of the fast is twice that the slow:

2(a + b) = a + b + k(b + c)

=> 2a + 2b = a + b + b + c + (k - 1)(b+ c)

=> (a - c) = (k - 1)(b + c)

142_2

What does it mean?

When the slow comes to the entry, the distance between the head and the slow is (k - 1)(b + c)

Then, if those two pointers keep moving, they will meet each other at the entry.

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

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is slow:
                while slow is not head:
                    slow = slow.next
                    head = head.next
                return slow
        return None

文章标题:142 Linked List Cycle II

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/142linked_list_cycle_ii[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。