- 我们遍历链表中的每个节点,并将它记录下来;一旦遇到了此前遍历过的节点,就可以判定链表中存在环。借助哈希表可以很方便地实现。
- 时间复杂度:O(N),其中 N 为链表中节点的数目。我们恰好需要访问链表中的每一个节点。
- 空间复杂度:O(N),其中 N 为链表中节点的数目。我们需要将链表中的每个节点都保存在哈希表当中。
- 此种方案需要额外占用存储空间存储已经遍历的节点
以下使用java语言编写此算法
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode pos = head;
Set<ListNode> visited = new HashSet<ListNode>();
while (pos != null) {
if (visited.contains(pos)) {
return pos;
} else {
visited.add(pos);
}
pos = pos.next;
}
return null;
}
}
我们使用两个指针,
fast
与slow
。它们起始都位于链表的头部。随后,slow
指针每次向后移动一个位置,而fast
指针向后移动两个位置。如果链表中存在环,则fast
指针最终将再次与slow
指针在环中相遇。如下图所示,设链表中环外部分的长度为 a。
slow
指针进入环后,又走了 b 的距离与fast
相遇。此时,fast
指针已经走完了环的 nn 圈,因此它走过的总距离为
a+n(b+c)+b=a+(n+1)b+nc
根据题意,任意时刻,fast
指针走过的距离都为 slow
指针的 2 倍。因此,我们有
a+(n+1)b+nc=2(a+b)⟹a=c+(n−1)(b+c)
有了 a=c+(n-1)(b+c)a=c+(n−1)(b+c) 的等量关系,
nb + nc = a + b
a = (n-1)b + nc
a = c + (n-1)b + (n-1)c
a= c + (n-1)(b+c)
我们会发现:从相遇点到入环点的距离加上 n-1n−1 圈的环长,恰好等于从链表头部到入环点的距离。
因此,当发现slow
与 fast
相遇时,我们再额外使用一个指针 ptr。起始,它指向链表头部;随后,它和 slow
每次向后移动一个位置。最终,它们会在入环点相遇。
以下使用java元进行实现
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast != null) {
slow = slow.next;
if (fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
if (fast == slow) {
ListNode ptr = head;
while (ptr != slow) {
ptr = ptr.next;
slow = slow.next;
}
return ptr;
}
}
return null;
}
}
思路二的复杂度为
时间复杂度:O(N),其中 N 为链表中节点的数目。在最初判断快慢指针是否相遇时,\textit{slow}slow 指针走过的距离不会超过链表的总长度;随后寻找入环点时,走过的距离也不会超过链表的总长度。因此,总的执行时间为 O(N)+O(N)=O(N)。
空间复杂度:O(1)O(1)。我们只使用了 slow, fast,ptr 三个指针。