环检测算法(Floyd's Tortoise and Hare)

Cycle Detect

环检测算法常用检测链表是否有环,如果有环,给出环的长度和环的入口点。
相关题目: 287. Find the Duplicate Number141. Linked List Cycle,142. Linked List Cycle II
参考:Leetcode solution简书-面试算法:链表成环

分析

当兔子和乌龟在环形跑道上跑步,在某一时刻,兔子会追上乌龟。

算法

算法可以分成两个步骤,第一个步骤是确定链表是否有环,第二个步骤是确定环的入口点在那里。

步骤1

首先,我们初始化两个指针,一个快速的 hare 指针,一个慢的Tortoise 指针。让hare 一次走两个节点,Tortoise 一个节点。最终,Tortoise 和hare 总会在相同的节点相遇,这样就可以证明是否有环。

《环检测算法(Floyd's Tortoise and Hare)》 image.png

这里,循环中的节点已经被标记为0到 C-1,在这里 C是环的长度。非环节点已经被标记 -F到-1,在这里F是环外的节点数量。在F次迭代后,tortoise指向节点0,并且hare指向某个节点 h。​​这是因为hare遍历2F节点的过程遍历了F次,F点仍在循环中。后面迭代C – h次,tortoise显然指向节点C – h,但hare也指向相同的节点。要明白为什么,请记住hare遍历2(C – h )从其起始位置开始H:

​h+2(C−h)​=2C−h​≡C−h(modC)

因此,鉴于列表是有环的,hare和tortoise最终都将指向同一个节点,所以这个节点可以作为后续的第一次相遇的点。

步骤2

考虑到步骤1发现一个交叉点,步骤2继续寻找环入口的节点。为此,我们初始化两个指针:ptr1指向列表头部的指针,指向ptr2交叉点的指针 。然后,我们把他们每个每次前进1个节点,直到他们相遇; 他们相遇的节点是环的入口,我们就可以得出结果。

《环检测算法(Floyd's Tortoise and Hare)》 image.png

我们可以利用hare移动步数是tortoise的两倍,以及tortoisehare和tortoise节点在h相遇,hare已经遍历了两倍的节点。使用这个事实,我们推导出以下内容:

2⋅distance(tortoise)​=distance(hare)
​2(F+a)​=F+a+b+a
​2F+2a​=F+2a+b
​F​=b

因为 F = b,指针从节点开始h和0在相遇之前, 将遍历相同数量的节点。

代码

public class Solution {
    private ListNode getIntersect(ListNode head) {
        ListNode tortoise = head;
        ListNode hare = head;

        // A fast pointer will either loop around a cycle and meet the slow
        // pointer or reach the `null` at the end of a non-cyclic list.
        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;
            hare = hare.next.next;
            if (tortoise == hare) {
                return tortoise;
            }
        }

        return null;
}

    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }

        // If there is a cycle, the fast/slow pointers will intersect at some
        // node. Otherwise, there is no cycle, so we cannot find an entrance to
        // a cycle.
        ListNode intersect = getIntersect(head);
        if (intersect == null) {
            return null;
        }

        // To find the entrance to the cycle, we have two pointers traverse at
        // the same speed -- one from the front of the list, and the other from
        // the point of intersection.
        ListNode ptr1 = head;
        ListNode ptr2 = intersect;
        while (ptr1 != ptr2) {
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }

        return ptr1;
    }
}
    原文作者:有苦向瓜诉说
    原文地址: https://www.jianshu.com/p/4f7dc8b9aa3c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞