LeetCode:M-142. Linked List Cycle II

来源:互联网 发布:各国语言在线翻译软件 编辑:程序博客网 时间:2024/06/10 15:57

LeetCode链接


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?


1、快慢指针,如果快指针追上慢指针,则表示有环

1)快慢指针起始都是head

2)快指针每次走2步,慢指针每次走1步

3)经过k步,快指针追上慢指针

2、查找环的开始点

1)设head到环的开始位置的步长为s

2)设环的开始位置到快慢指针相遇点,经过步长m,则 k=s+m -> s=k-m

3)设环的长为r步长,则快慢相遇时 k+nr=2k -> k=nr

4)由2),s = k-m = nr - m = (n-1)r + (r-m),r-m为快慢相遇点到环起点的距离

5)从head和快慢相遇点同时开始遍历,head会走s步, 快慢相遇点会走 (n-1)r + (r-m)步,由于(n-1)r就是绕环,不影响两者的相遇,遍历的相遇点就是环的开始点


TC = O(n)

/** * 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) {        if(head==null) return null;                ListNode slow=head;        ListNode fast=head;            boolean hasCycle=false;        while(fast.next!=null && fast.next.next!=null){            slow=slow.next;            fast=fast.next.next;                if(slow==fast){                    hasCycle=true;                    break;                }                            }                            if(hasCycle){            slow = head;            while(slow != fast){                slow=slow.next;                fast=fast.next;            }            return slow;        }        return null;}}