【Leetcode 142】Linked List Cycle II
难度: 中等(Medium)
题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
解题思路
证明:
设
p1与p2相遇时用时为t,
p1在圈内走了n1圈
p2在圈内走了n2圈
圈长为l
起点到成环点距离为x
相遇点到起点距离为z
成环点到相遇点距离为y
则
2t - t = (n2 - n1) * l => t = (n2 - n1) * l
t + z = x + (n1 + 1) * l
t = (n2 - n1) * l
z + (n2 - n1) * l = x + (n1 + 1) * l
x = z + (n2 - 2*n1 - 1) * l
所以p1在相遇点接着走,p2从起点开始走,同时同步走下次会在成环点相遇
代码
1 | # Definition for singly-linked list. |
评论系统未开启,无法评论!