-
Notifications
You must be signed in to change notification settings - Fork 6
/
LinkedListCycleII.java
74 lines (71 loc) · 1.82 KB
/
LinkedListCycleII.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package io.ziheng.list.leetcode;
import java.util.HashSet;
import java.util.Set;
import io.ziheng.list.leetcode.ListNode;
/**
* LeetCode 142. Linked List Cycle II
* https://leetcode.com/problems/linked-list-cycle-ii/
*/
public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
// return detectCycleHashing(head);
return detectCycleTwoPointer(head);
}
/**
* Linked List Detect Cycle -> Two Pointer
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @param head
* @return ListNode
*/
private ListNode detectCycleTwoPointer(ListNode head) {
boolean hasCycle = false;
ListNode pSlow = head;
ListNode pFast = head;
while (pFast != null && pFast.next != null) {
pSlow = pSlow.next;
pFast = pFast.next.next;
if (pSlow == pFast) {
hasCycle = true;
break;
}
}
if (!hasCycle) {
return null;
}
ListNode pA = head;
ListNode pB = pFast;
while (pA != pB) {
pA = pA.next;
pB = pB.next;
}
return pA;
}
/**
* Linked List Detect Cycle -> Hashing
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @param head
* @return ListNode
*/
private ListNode detectCycleHashing(ListNode head) {
Set<ListNode> aSet = new HashSet<>();
ListNode currentNode = head;
while (currentNode != null) {
if (aSet.contains(currentNode)) {
return currentNode;
}
aSet.add(currentNode);
currentNode = currentNode.next;
}
return null;
}
}
/* EOF */