• 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;
        }
    }
  • 相关阅读:
    ffmpeg影片转码+m3u8-segmenter影片切片
    Linux ffmpeg安装步骤详解
    linux系统部署ffmpeg视频转码环境及使用方法
    SSH反向连接使用Autossh自动ssh
    WordPress整合Google自定义搜索
    优化Wordpress的方法总结
    WordPress 数据库操作WPDB对象($wpdb)用法详解
    WordPress插件WP-PostViews的调用方法
    国内大互联网公司如何做测试
    一分钟了解ruby中的单测
  • 原文地址:https://www.cnblogs.com/joannacode/p/6121454.html
Copyright © 2020-2023  润新知