zoukankan      html  css  js  c++  java
  • 142. Linked List Cycle II

    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.

    使用快慢指针,

    fast每次前进两步(若两步中出现NULL,则返回NULL).

    slow每次前进一步(若出现NULL,则返回NULL).

    当出现环路,则总有某时刻,fast会赶上slow(相遇),证明如下:

    1、若fast套slow圈之前在slow后方两步,则fast2slow1之后,fast在slow后方一步,进入(2)

    2、若fast套slow圈之前在slow后方一步,则fast2slow1之后,fast追上slow(相遇)

    其他情况均可化归到以上两步。

    假设从head到环入口entry步数为x,环路长度为y,相遇时离entry的距离为m

    则fast:x+ay+m,slow:x+by+m  (a > b)

    x+ay+m = 2(x+by+m)

    整理得x+m = (a-2b)y

    以上式子的含义是,相遇时的位置(m)再前进x步,正好是y的整倍数即整圈。

    现在的问题是怎样计数x。

    利用head到entry的长度为x,只要fast从head每次前进一步,slow从相遇位置每次前进一步,

    再次相遇的时候即环的入口。

    /**
     * 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 || head.next == null) return null;
            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 slow;
        }
    }
  • 相关阅读:
    运算符和表达式详解
    超实用的Java web面试题
    80道最新java基础部分面试题(七)
    80道最新java基础部分面试题(六)
    80道最新java基础部分面试题(五)
    12道算法与编程面试题
    javaee和javase的区别
    2019年最新50道java基础部分面试题(四)
    2019年最新50道java基础部分面试题(三)
    2019年最新50道java基础部分面试题(二)
  • 原文地址:https://www.cnblogs.com/joannacode/p/6121454.html
Copyright © 2011-2022 走看看