Skip to content

Commit 1982557

Browse files
committed
✨ [141] Floyd's algorithms
1 parent 6c7819a commit 1982557

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

141/my_solution.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* @param {ListNode} head
11+
* @return {boolean}
12+
*/
13+
const hasCycle = (head) => { // Bad memory O(n)
14+
let hashMap = new Map();
15+
16+
while (null !== head) {
17+
if (undefined !== hashMap.get(head)) return true;
18+
19+
hashMap.set(head, 0);
20+
head = head.next;
21+
}
22+
23+
return false;
24+
}

141/solution.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* @param {ListNode} head
11+
* @return {boolean}
12+
*/
13+
const hasCycle = (head) => { // O(n), O(1)
14+
let slow = head, fast = head;
15+
16+
while (null !== fast && null !== fast.next) {
17+
slow = slow.next;
18+
fast = fast.next.next;
19+
if (slow == fast) return true;
20+
}
21+
22+
return false;
23+
}

0 commit comments

Comments
 (0)