lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

      • 21. 合并两个有序链表
      • 141. 环形链表
      • 142. 环形链表 II
      • 160. 相交链表
      • 203. 移除链表元素
      • 206. 反转链表
      • 234.回文链表
    • 栈

    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • list
2023-04-29

环形链表 II

https://leetcode.cn/problems/linked-list-cycle-ii/ (opens new window) 需要注意的点 1. 环头节点(环头),链表的头节点(链头),fast 跟slow 相遇的节点(相遇点) 走n圈,环头到链头为a,slow 到相遇点为b, fast 在环里面走c, 环的长度是b+c fast走过的距离是 fast = a + n(b+c)+b = a + (n+1)b+nc slow走过的距离是 slow = a+b 等式 a + (n+1)b+nc = 2(a+b) == a = c + (n-1)(b+c)

# 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:

        '''
        环头节点(环头),链表的头节点(链头),fast 跟slow 相遇的节点(相遇点)
        走n圈,环头到链头为a,slow 到相遇点为b, fast 在环里面走c,
        环的长度是b+c
        fast走过的距离是
        fast = a + n(b+c)+b = a + (n+1)b+nc
        slow走过的距离是
        slow = a+b
        等式
        a + (n+1)b+nc = 2(a+b)
        == a = c + (n-1)(b+c)
        '''
        slow = head
        fast = head

        while fast and fast.next:

            fast = fast.next.next
            slow = slow.next

            if fast == slow:

                a = fast
                b = head

                while a != b:
                    a = a.next
                    b = b.next
                
                return a

        return None
141. 环形链表
160. 相交链表

← 141. 环形链表 160. 相交链表→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式