算法修炼之路——【链表】Leetcode142 环检测 II

问题描述

给定一个链表,返回链表开始入环的第一个节点。如果链表无环,则返回null

为了表示给定链表中的环,我们使用整数 pos来表示链表尾连接到链表中的位置(索引从0开始)。如果pos-1,则在该链表中没有环。

说明:不允许修改给定的链表
示例1:

输入: head=[3,2,0,-4], pos = 1
输出: tail connects to node index 1
解释: 链表中有一个环,其尾部连接到第二个节点。

在这里插入图片描述
图1 例题1

示例2:

输入: head=[1,2], pos = 0
输出: tail connects to node index 1
解释: 链表中有一个环,其尾部连接到第二个节点。

在这里插入图片描述
图2 例题2

解题思路

题干中提取信息:
数据结构:链表;
功能要求:环检测;
返回信息:若环存在,则返回环的第一个节点;若不存在,返回null;
特殊说明:不允许改变链表,即原地算法;

对于2,我们通过Leetcode141已经获知环检测的算法,即快慢指针;
考虑3,需要在检测到环之后,查找到第一个节点,需要在环检测升级找到其第一个节点:我们不妨以例题1为思考图,环的第一个节点为节点2,其特点为存在两个不同的前置节点,此时的一个解题思路是遍历过程中记录下走过的节点并存储,第一个重复键即为环首节点,下面进行编程:

解题代码1

import java.util.Set;
import java.util.HashSet;

class ListNode{

   int val;
   ListNode next;
   ListNode(int x) {
      val = x;
      next = null;
  }
}

//solution 1: fast&slow pointers with set deceting unique keys
    public static ListNode solutionWithCon(ListNode head) {
        //pre-judge head's reationality
        if (head == null || head.next == null) {
            return null;
        }
        Set<ListNode> set = new HashSet<>();
        ListNode pointer = head;

        //1. detect the cycle
        while (pointer != null) {
            // 2. find the cycle
            if (set.contains(pointer)) {
                return pointer;
            }
            set.add(pointer);
            pointer = pointer.next;
        }
        return null;
    }

复杂度分析

我们分析一下solutionWithCon的复杂度,这里为方便,我们假设链表长度为N=F+a+b,非环部分占节点F, 环节点占a+b:
在这里插入图片描述
图3

时间复杂度:solutionWithCon仅需一个节点,访问了(F+a+b)个节点,时间复杂度为O(N);
空间复杂度:solutionWithCon需要一个集合作为辅助数据结构,空间复杂度为O(N);

进阶思考

是否存在空间复杂度为O(1)的情况下完成题干要求?
我们可以通过图3进行抽象思考,在检测环的时候,还假设快慢指针,快指针走过的距离(节点数)为(F+a+b+a),慢指针走过的距离为(F+a),我们需要求第F个节点,根据快指针走过的节点数为慢指针的二倍我们可知:

2distance(slowP) = distance(fastP)
2
(F+a) = F+a+b+a
F = b (1)

我们通过图3,又知道,相遇的时刻slowP经过b会再次回到首节点,那么如何限定到这个不知道具体数值的b呢?从公式(1)可知,从head节点走到初始节点则为环首节点,此时根据这两个条件就可以判断,slowP单步走,另一个指针从head节点单步走,相遇的节点即为环的首节点,此时,有第二个解法solutionWithTwoP:

解题代码2

   public static ListNode solutionWithTwoP(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slowP = head;
        ListNode fastP = head;

        // 1. detect cycle
        while (fastP != null && fastP.next != null) {
            slowP = slowP.next;
            fastP = fastP.next.next;

            //2. find the start-node of cycle
            if (slowP == fastP) {
                ListNode node = head;
                while (node != slowP) {
                    node = node.next;
                    slowP = slowP.next;
                }
                return slowP;
            }
        }
        return null;
    }

复杂度分析

时间复杂度:此时时间复杂度为O(N);
空间复杂度:没有辅助数据结构,故为O(1);

GitHub代码

完整代码文件请访问GitHub

发布了47 篇原创文章 · 获赞 55 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u011106767/article/details/105215532