您的位置:首页 > 其它

LeetCode 142 Linked List Cycle II

2016-04-14 16:11 267 查看
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.

Follow up:

Can you solve it without using extra space?

具体过程及证明见:代码过程证明

另外再附加一段:F可能超了S很多圈的:假设刚进环的时候慢指针走了m步,环的大小为n,快慢指针在距离环起点x步的时候相遇。慢指针是一定走不完一圈就会和快指针相遇的(因为最惨的情况下就是慢指针进圈的时候快指针在它前面一个,快指针速度时慢的两倍,这种悲剧情况下慢指针也不可能走完一圈就会被追到)。这是慢指针走了m+x步,快指针走了2(m+x)步,快指针在圈内走了2(m+x)-m=m+2x步。由于相遇在x位置,所以
m+2x % n = x,推出m+2x = i * n + x,于是m+x = i*n。我们注意到慢指针已经走了x步了,再走m步时一定会回到圈的起点的(m+x = i*n),所以等它们相遇后,一个指针从head开始走,然后慢指针从相遇的位置出发,则一定会相遇到圈的起点。

public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode slow = head,fast = head;
while (slow != null && fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
fast=head;
while (fast!=slow) {
fast= fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: