File tree 2 files changed +47
-0
lines changed
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments