zoukankan      html  css  js  c++  java
  • [LeetCode题解]142. 环形链表 II | 快慢指针

    解题思路

    本题是在141. 环形链表基础上的拓展,如果存在环,要找出环的入口。

    如何判断是否存在环,我们知道通过快慢指针,如果相遇就表示有环。那么如何找到入口呢?

    如下图所示的链表:

    环形链表

    fastslow 第一次相遇时,有以下关系:

    fast = 2 * slow
    slow = a + n*b - c // 假设 slow 走了 n 圈
    fast = a + m*b - c // 假设 fast 走了 m 圈
    那就有:
    a + m*b - c = 2*(a + n*b - c)
    继而得到:
    a = c + (m-n)*b
    而(m-n)*b表示走了 m-n 圈,不影响 c 的大小,即可忽略,最终得到:
    a = c
    

    通过上面的推导,我们知道相遇点距环的入口的距离(c)与开头到环的入口的距离(a)相等。

    因此当 fastslow 相遇时,只要 fast 重新定位到表头,与 slow 一起走,当它们再次相遇时,就是环的入口。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode DetectCycle(ListNode head) {
            ListNode fast = head, slow = head;
            while(fast != null && fast.next != null){
                fast = fast.next.next;
                slow = slow.next;
    
                if(fast == slow) { // 存在环
                    fast = head;
                    while(fast != slow) {
                        fast = fast.next;
                        slow = slow.next;
                    }
                    return fast;
                }
            }
            return null;
        }
    }
    

    复杂度分析

    • 时间复杂度:(O(n)),其中 (n) 是链表长度
    • 空间复杂度:(O(1))
  • 相关阅读:
    网络受限下,使用Nexus要解决的两个问题
    Nexus远程Maven仓库索引下载教程
    maven--私服的搭建(Nexus的使用)
    maven命令/依赖/聚合
    mybatis常用jdbcType数据类型
    Lombok 安装、入门
    jquery append 动态添加的元素事件on 不起作用的解决方案
    Maximum Sum on Even Positions
    哈密顿
    计算几何基础
  • 原文地址:https://www.cnblogs.com/liang24/p/14011561.html
Copyright © 2011-2022 走看看