File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-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
+ var hasCycle = function ( head ) {
14
+ // ์ํํ์ง ๊ธฐ๋ฒ
15
+ // 1. ํ๋ก์ด๋ ํ ๋ผ์ ๊ฑฐ๋ถ์ด (ํฌ์ธํฐ2๊ฐ)
16
+ // 2. ์งํฉ์ ํตํ ์ค๋ณต๊ฒ์ฌ
17
+
18
+ ////////ํ์ด///////
19
+
20
+ // ๋
ธ๋ 0๊ฐ 1๊ฐ๋ฉด ์ํ๋ถ๊ฐ
21
+
22
+ if ( ! head || ! head . next ) {
23
+ return false ;
24
+ }
25
+
26
+ // ํ ๋ผ, ๊ฑฐ๋ถ์ด ์ค์
27
+ let slow = head ;
28
+ let fast = head . next ;
29
+
30
+ while ( slow !== fast ) {
31
+ // ๋์นธ์ ์ง์ ๋
ธ๋ ์กด์ฌ ์ฒดํฌ
32
+ if ( ! fast || ! fast . next ) {
33
+ return false ;
34
+ }
35
+
36
+ slow = slow . next ;
37
+ fast = fast . next . next ;
38
+ }
39
+
40
+ return true ;
41
+ } ;
42
+
43
+ // ์๊ฐ๋ณต์ก๋ O(n) -> ์ต๋ ๋ฆฌ์คํธ์ ๋
ธ๋ ์ ๋งํผ while๋ฌธ์ด ๋ฐ๋ณต๋๋ฏ๋ก
44
+ // ๊ณต๊ฐ๋ณต์ก๋ O(1) -> ํ ๋ผ, ๊ฑฐ๋ถ์ด ํฌ์ธํฐ 2๊ฐ๋ง ์ฌ์ฉํ๋ฏ๋ก
You canโt perform that action at this time.
0 commit comments