LeetCode题解:Linked List Cycle II

来源:互联网 发布:淘宝客新建导购推广 编辑:程序博客网 时间:2024/06/06 03:57

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?

题意:给定链表,返回环的起点;若不存在起点,返回null。要求:O(1)空间

思路:快慢指针,只是要注意一个小细节帮助我们找到起点:假如指针能够相遇,则必有快指针的总路程减去慢指针的总路程等于环长度的倍数,否则是不可能相遇的。

那么假设到达相遇点时慢指针走的步数为t,则有2t-t=n*l,其中n代表绕环的次数,[0,…),l表示环的长度。

现在假设从环起点到相遇点的距离为m,此时有:

从相遇点到环起点的距离为m’=l-m,从起点到环起点的距离为r=t-m,即m=t-r。所以m’=l-t+r=(1-n)*l+r,即r=m’+(n-1)l。也就是说r和m’是相等的。利用这个性质就可以找到起点了

代码:

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode detectCycle(ListNode head) {        ListNode slow = head;        ListNode fast = head;        while(fast != null && fast.next != null){            slow = slow.next;            fast = fast.next.next;            if(slow == fast){                break;            }        }        if(fast == null || fast.next == null){            return null;        }        slow = head;        while(slow != fast){            slow = slow.next;            fast = fast.next;        }        return fast;    }}
0 0
原创粉丝点击