LeetCode刷题之链表 第142题 环形链表Ⅱ

题目描述

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

示例

在这里插入图片描述
输入: head = [3,2,0,-4], pos = 1
输出: 返回索引为 1 的链表节点

方法一:HashSet

思路

新建一个ListNode类型的HashSet,遍历链表的节点,并添加到HashSet中,如果在HashSet中遇到了之前遍历过的节点,说明链表存在环

代码

/**
 
/**
 * 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) {
        Set<ListNode> set = new HashSet<>();
        while(head != null){
            if(set.contains(head)){
                return head;
            }
            set.add(head);
            head = head.next;
        }
        return null; 
    }
}

复杂度分析

时间复杂度:O(n),其中n是链表中节点的数目
空间复杂度:O(n)

方法二:双指针

思路

在这里插入图片描述

使用两个指针 fas t和 slow,它们都起始于链表的头节点,fast 指针每次移动两个位置, slow 指针每次移动一个位置,如果链表存在环,那么 slow 和 fast 指针最后一定会在环中相遇。假设从头节点到环的入口的距离为 x,slow 指针在环中移动 y 距离后与 fast 指针相遇,相遇时 fast 指针已经在环中走了 n 圈。此时 slow 指针走过的距离是 x+y,fast 指针走过的距离是 x+n(y+z)+y=x+(n+1)y+z。在任意时刻, fast指针走过的距离都是 slow 指针走过距离的 2 倍,故 x+(n+1)y+z=2(x+y) ---->> x=(n-1)(y+z)+z,即从头节到环的入口节点的距离等于环入口节点到相遇节点的距离加上 n-1 倍的环的长度。所以相遇时,使用两个指针,一个从链表头节点出发,一个从相遇节点出发,两个指针每次均移动一个位置,那么这两个指针相遇的位置即为环的入口节点。

JAVA代码


/**
 * 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) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                ListNode index1 = head;
                ListNode index2 = slow;
                while(index1 != index2){
                    index1 = index1.next;
                    index2 = index2.next;
                }
                return index1;
            }  
        }
        return null;
    }
}

复杂度分析

时间复杂度:O(n),假设 n 是链表中节点的数目
空间复杂度:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值