Leetcode142. Linked List Cycle II

Leetcode142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

在这里插入图片描述
Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

在这里插入图片描述
Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

在这里插入图片描述

判断是否有环,如果有那需要找到环的入口点

解法一 哈希表
public ListNode detectCycle(ListNode head) {
    HashSet<ListNode> set = new HashSet<>();
    while (head != null) {
        set.add(head);
        head = head.next;
        if (set.contains(head)) {
            return head;
        }
    }
    return null;
}
解法二 快慢指针

设两指针 fastslow 指向链表头部 headfast 每轮走 2 步,slow 每轮走 1 步;链表头部到链表环入口有a个节点(不计链表环入口节点),链表环有b个节点。(注意ab都是未知量)

fast 指针走过链表末端,说明链表无环。若有环,两指针一定会相遇。因为每走 1 轮,fast 与 slow 的间距 +1。

② 两指针在环中第一次相遇,设此时两指针分别走了fs

  1. fast 走的步数是slow步数的 2 倍:f = 2s
  2. fastslow多走了 n 个环的长度:f = s + nb (双指针都走过a步,然后在环内绕圈直到重合,重合时fastslow多走了环的长度整数倍)
  3. 两式相减,得到s = nbf = 2nb。即fastslow指针分别走了 2nn个环的周长(n是未知数)

一个重要结论:任何一个指针从链表头部开始向前走,当它每次走到链表入口节点时,它所走过的步数k = a + nb (先走 a 步到入口节点,之后每绕 1 圈环( b 步)都会再次到入口节点)。

③ 两指针第一次相遇时,slow指针已经走过了nb步,所以我们只要让 slow 再走 a 步停下来,就可以到环的入口。但是问题是a是未知数,需要找到一个条件来证明snow刚好走过了a步,发现从链表头部开始走到链表环的入口刚好是a步。

  1. slow指针位置不变 ,将fast指针重新指向链表头部节点 ;slowfast同时每轮向前走 1 步。
  2. fast指针走到f = a步时,slow指针走到步s = a+nb,此时两指针重合,并同时指向链表环入口 。

④ 返回slow指针指向的节点

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

在这里插入图片描述

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while (true) {
            if (fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值