-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo141LinkedListCycle.java
58 lines (48 loc) · 1.19 KB
/
No141LinkedListCycle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.wzx.leetcode;
import com.wzx.entity.ListNode;
import java.util.HashSet;
import java.util.Set;
/**
* @see <a href="https://leetcode.com/problems/linked-list-cycle/">https://leetcode.com/problems/linked-list-cycle/</a>
* @author wzx
*/
public class No141LinkedListCycle {
/**
* time: O(n)
* space: O(n)
*/
public boolean hasCycle1(ListNode head) {
Set<ListNode> nodeSet = new HashSet<>();
while (head != null) {
if (nodeSet.contains(head)) {
return true;
} else {
nodeSet.add(head);
head = head.next;
}
}
return false;
}
/**
* 快慢指针
* 设总长为n,环长k,非环部分为n-k
* 当慢指针刚进入环时,快指针已经在环中,迭代了n-k次
* 快指针最慢需要k次迭代就能在环中追上慢指针,迭代了k次
* 总共 n-k+k=n
* <p>
* time: O(n)
* space: O(1)
*/
public boolean hasCycle2(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null && slow != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}