We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
leetcode 上这道题如果有map的方式可以很容易的解决,但是如果我们想用快慢指针的方式解决这道题,虽然从代码的层面上来看任然很简单,但是如果你想严谨的去证明为什么这样可以就不太容易了,看了很多人的分析,但是感觉证明过程都不太严谨,所以这里写一篇严谨的证明过程.
快指针的速度是慢指针的两倍,首先我们假设是有环的,我们需要先假设几个变量
x
y
l
当快慢相遇时,假设快指针在圆环内跑了 n 圈,慢指针跑了 m圈.
x + l * n + y
x + l * m + y
2(x + l * n + y) = x + l * m + y
x + y = l(m - 2n)
x + y = kl
x = kl - y
kl
The text was updated successfully, but these errors were encountered:
/** * @param {ListNode} head * @return {ListNode} */ const detectCycle = function(head) { let quick = head; let slow = head; while (quick) { quick = quick.next ? quick.next.next : null; slow = slow.next; if (quick === slow && quick !== null) { break; } } if (!quick) { return null } quick = head; while (quick !== slow) { quick = quick.next; slow = slow.next; } return quick; };
Sorry, something went wrong.
No branches or pull requests
leetcode 上这道题如果有map的方式可以很容易的解决,但是如果我们想用快慢指针的方式解决这道题,虽然从代码的层面上来看任然很简单,但是如果你想严谨的去证明为什么这样可以就不太容易了,看了很多人的分析,但是感觉证明过程都不太严谨,所以这里写一篇严谨的证明过程.
证明
快指针的速度是慢指针的两倍,首先我们假设是有环的,我们需要先假设几个变量
x
y
l
当快慢相遇时,假设快指针在圆环内跑了 n 圈,慢指针跑了 m圈.
x + l * n + y
, 快指针走过的距离为x + l * m + y
2(x + l * n + y) = x + l * m + y
,x + y = l(m - 2n)
, 因为 m 和 n都为整数,所以 m -2n也为整数,x + y = kl
, k 为整数, 推导得x = kl - y
y
, 如果从相遇点走多x
步, 则会到距离圆环切入点kl
的位置,刚好就是圆环的切入点The text was updated successfully, but these errors were encountered: