-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-104-linkedListCycle-2.js
72 lines (56 loc) · 1.38 KB
/
structy-104-linkedListCycle-2.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
67
68
69
70
71
72
// class Node {
// constructor(val) {
// this.val = val;
// this.next = null;
// }
// }
// _______
// / \
// a -> b -> c -> d
// p: head of ll
// r: boolean
// 2 pointers O(n) O(1)
const linkedListCycle = (head) => {
let slow = head;
let fast = head;
let firstMeet = true;
while (fast && fast.next) {
if (slow.val === fast.val && !firstMeet) return true;
slow = slow.next;
fast = fast.next.next;
firstMeet = false;
}
return false;
};
// // 2 pointers O(n) O(1)
// const linkedListCycle = (head) => {
// if (!head || !head.next) return false;
// let slow = head;
// let fast = head.next;
// while (slow && fast) {
// if (slow.val === fast.val) return true;
// slow = slow.next;
// if (!fast.next) {return false;}
// else fast = fast.next.next;
// }
// return false;
// }
// recursive O(n) O(n)
const linkedListCycle = (head, visited = new Set()) => {
if (!head) return false;
if (visited.has(head.val)) return true;
visited.add(head.val);
if (linkedListCycle(head.next, visited)) return true;
return false;
};
// // iterative O(n) O(n)
// const linkedListCycle = (head) => {
// let current = head;
// let visited = new Set();
// while (current) {
// if (visited.has(current.val)) return true;
// visited.add(current.val);
// current = current.next;
// }
// return false;
// };