Skip to content

Commit 60282fc

Browse files
committed
fix: linked-list-cycle 토끼와 거북이 알고리즘 적용
1 parent 867f27f commit 60282fc

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

linked-list-cycle/YeomChaeeun.ts

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,33 @@
1313
* 순환되는 링크드 리스트 찾기
1414
* 알고리즘 복잡도
1515
* - 시간 복잡도: O(n)
16-
* - 공간 복잡도: O(n)
16+
* - 공간 복잡도: O(1)
1717
* @param head
1818
*/
1919
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+
}
2642
}
43+
2744
return false
2845
}

0 commit comments

Comments
 (0)