这是一道 中等难度 的题,是基于 【算法题解】10. 判断链表是否有环 的扩展。
题目来自:https://leetcode.cn/problems/linked-list-cycle-ii/description/
题目
示例1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
示例2:
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。
示例3:
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
提示:
-
链表中节点的数目范围在范围
[0, 104]
内 -
-105 <= Node.val <= 105
-
pos
的值为-1
或者链表中的一个有效索引
进阶:你是否可以使用 O(1)
空间解决此题?

解法一:循环标记
01
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) {
Set<ListNode> visited = new HashSet<>();
while(head != null){
if(visited.contains(head)){
return head;
}
visited.add(head);
head = head.next;
}
return null;
}
}
02
Go 代码实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
visited := make(map[*ListNode]bool)
for head != nil {
if visited[head]{
return head;
}
visited[head] = true
head = head.Next
}
return nil
}
03
复杂度分析
时间复杂度 O(N):需要访问链表中的每一个节点,时间复杂度为链表长度 n。
空间复杂度 O(N):需要记录每个访问过的节点,空间复杂度为链表的长度 n。

解法二:快慢指针

01
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, slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
// 第一次相遇
if(slow == fast){
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
// 第二次相遇
return fast;
}
}
return null;
}
}
02
Go 代码实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
fast, slow := head, head
for fast != nil && fast.Next != nil {
fast, slow = fast.Next.Next, slow.Next
if(slow == fast){
fast = head
for fast != slow {
fast, slow = fast.Next, slow.Next
}
return fast
}
}
return nil
}
03
复杂度分析

点个
原文始发于微信公众号(i余数):【算法题解】11. 判断链表是否有环,并返回入环节点
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/194015.html