`

LeetCode 142 - Linked List Cycle II

 
阅读更多

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?


 
算法参见Wekipedia.

1. 假设圈的周长λ,相遇的时候乌龟走的路程:μ + k, 而兔子走的路程:μ + k + n*λ,(n代表兔子走了多少圈)

2. 因为兔子的速度是乌龟的两倍,所以兔子走的路程是乌龟的两倍,2(μ + k) = μ + k + n*λ,得到μ = n*λ - k = (n-1)λ + (λ-k)

3. 从相遇点的时候开始,乌龟从开始点走起,兔子从相遇点继续走,而且这时两者走的速度是一样的,那么当乌龟从头走到循环点X的时候,走了μ路程,而兔子走的路程是n*λ - k,两者的路程是一样的,相遇点必然是X。

 

public ListNode detectCycle(ListNode head) {
    ListNode walker = head, runner = head;
    do {
        if(runner == null || runner.next == null) {
            return null;
        }
        walker = walker.next;
        runner = runner.next.next;
    } while(walker != runner);
    
    walker = head;
    while(walker != runner) {
        walker = walker.next;
        runner = runner.next;
    }
    return walker;
}

 

  • 大小: 40.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics