-
Notifications
You must be signed in to change notification settings - Fork 0
/
0142. Linked List Cycle II.js
66 lines (55 loc) · 1.21 KB
/
0142. Linked List Cycle II.js
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
// Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
//
// Note: Do not modify the linked list.
//
// Follow up:
// Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
/** 1) Hash set */
// Time O(n)
// Space O(n)
const detectCycle1 = (head) => {
const visited = new Set();
let node = head;
while (node != null) {
if (visited.has(node)) return node;
visited.add(node);
node = node.next;
}
return null;
};
/** 2) Floyd's Tortoise and Hare */
// Time O(n)
// Space O(1)
const detectCycle = (head) => {
if (head == null) return null;
const getIntersect = (head) => {
let slow = head;
let fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return fast;
}
return null;
};
const intersect = getIntersect(head);
if (intersect == null) return null;
let slow = head;
let fast = intersect;
while (slow !== fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
};