标签:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
同Leetcode 141 Linked List Cycle
性质:distance from head to 环开始点 == distance from 双指针相遇的点 to 环开始点
证明:
指针a速度为1 指针b速度为2
记head到环开始处的距离为k,环的周长为r,从环开始处顺方向到相遇点的距离为d
则a到相遇点走过的路程为 Sa = k + d, Sb= k + nr + d (n为b多绕的圈数)
取n= 1 时 Sb = k + r + d 同时要满足 Sa * 2 = Sb
则 d = r - k, Sa = r, Sb = 2r 满足条件
显然 不存在n>1 使得成立的情况
var detectCycle = function(head) { if(!head) return null var a = head var b = head while(b.next && b.next.next){ b = b.next.next a = a.next if(a===b){ a = head while(a !== b){ a = a.next b = b.next } return a } } return null }
Leetcode 142 Linked List Cycle II
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4589910.html