环形链表II 快慢指针

参考于:
https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-/
注意要用距离、几何来理解这道题
使用快慢指针

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if head == None:
            return None
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if not fast.next or not fast.next.next:
            return None
        count2 = 0
        fast = head
        while fast != slow:
            fast = fast.next
            slow = slow.next
            count2 += 1
        # 求环的大小
        # f = fast
        # s = slow
        # c = 0
        # while f.next and f.next.next:
        #     f = f.next.next
        #     s = s.next
        #     c += 1
        #     if s == f:
        #         print(c)
        #         break
        return fast

简单的写法:

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if not head:
            return None
        fast = head
        slow = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if not fast.next or not fast.next.next:
            return None
        fast = head
        while fast != slow:
            fast = fast.next
            slow = slow.next
        return slow

把关键的点,记录一下:
快指走过的路程是环形周长的整数倍,F= N*R 这点比较关键
另外,但慢指针走过的路程为(N*R+K)时,指针的位置一定处于环形的入口处
关于环中相遇的位置:
但慢指针刚好到达环的入口时,s距离f的距离为 δ x \delta x δx ,那么相遇的位置会是对称的y位置,解释如下:当他们相遇时,f要比s多走 R − δ x R-\delta x Rδx, 设时间为t, 2 t − t = R − δ x 2t-t =R-\delta x 2tt=Rδx, t = R − δ x t = R-\delta x t=Rδx, 因此相遇的位置是:对于s 0 + R − δ x 0+R-\delta x 0+Rδx 即 对称的位置 y y y

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值