File tree Expand file tree Collapse file tree 1 file changed +24
-7
lines changed Expand file tree Collapse file tree 1 file changed +24
-7
lines changed Original file line number Diff line number Diff line change 13
13
* 순환되는 링크드 리스트 찾기
14
14
* 알고리즘 복잡도
15
15
* - 시간 복잡도: O(n)
16
- * - 공간 복잡도: O(n )
16
+ * - 공간 복잡도: O(1 )
17
17
* @param head
18
18
*/
19
19
function hasCycle ( head : ListNode | null ) : boolean {
20
- let set = new Set ( ) ;
21
- while ( head !== null ) {
22
- // set에 이미 존재하는지 확인
23
- if ( set . has ( head ) ) return true
24
- set . add ( head )
25
- head = head . next
20
+ // 1. set을 이용한 풀이
21
+ // 시간 복잡도: O(n) , 공간 복잡도: O(n)
22
+ // let set = new Set();
23
+ // while(head !== null) {
24
+ // // set에 이미 존재하는지 확인
25
+ // if(set.has(head)) return true
26
+ // set.add(head)
27
+ // head = head.next
28
+ // }
29
+
30
+ // 2. 토끼와 거북이 알고리즘
31
+ // 포인터를 2개 이동하는 방법
32
+ let slow = head
33
+ let fast = head
34
+
35
+ while ( fast ?. next ) {
36
+ slow = slow . next
37
+ fast = fast . next . next
38
+
39
+ if ( slow === fast ) {
40
+ return true
41
+ }
26
42
}
43
+
27
44
return false
28
45
}
You can’t perform that action at this time.
0 commit comments