方法 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)