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;
        }
    }
  • 相关阅读:
    IOS开发中实现UITableView按照首字母将集合进行检索分组
    IOS开发中设置导航栏主题
    IOS中使用.xib文件封装一个自定义View
    IOS中将字典转成模型对象
    WindowsPhone8中LongListSelector的扩展解决其不能绑定SelectdeItem的问题
    WindowsPhone8.1 开发-- 二维码扫描
    tomcat 开机自启
    redis ubuntu 开机自启
    webStorm 中使用 supervisor 调试
    ubuntu 14.04 tab失效问题
  • 原文地址:https://www.cnblogs.com/joannacode/p/6121454.html
Copyright © 2011-2022 走看看