方法 1:哈希表
想法
如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。
class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
时间复杂度
时间复杂度: O(n),假设 n 是列表的长度,时间复杂度是 O(n)。
空间复杂度: O(1)
方法 2:快慢指针
想法
如果链表有环,慢指针每次移动一个节点,快指针每次移动两个节点,环形就像操场的环形跑道,假如一直跑下去,快的那个人一直跑下去,总会套圈慢的那个人,即两个人相遇,第一次相遇时,说明快的那个人比慢的人多跑了一圈。
class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
// 慢指针
ListNode a = head;
// 快指针
ListNode b = head.next;
while (b != null && b.next != null) {
if (a == b) {
return true;
}
a = a.next;
b = b.next.next;
}
return false;
}
}
时间复杂度
时间复杂度: O(n),假设 n 是列表的长度,时间复杂度是 O(n)。
空间复杂度: O(1)