File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ // ## 🔗 문제 링크
2
+ // https://leetcode.com/problems/linked-list-cycle/
3
+
4
+ // ## ✨ 문제 요약
5
+ // 연결 리스트에 사이클이 있는지 여부를 판별하는 문제입니다.
6
+
7
+ // ## ✅ 풀이 방법
8
+ // ### 1. HashSet 사용
9
+ // - 방문한 노드를 저장하고 중복 방문 시 true
10
+ // - 시간복잡도: O(n), 공간복잡도: O(n)
11
+
12
+ var hasCycle = function ( head ) {
13
+ let visited = new Set ( ) ;
14
+ let current = head ;
15
+
16
+ while ( current !== null ) {
17
+ if ( visited . has ( current ) ) {
18
+ return true ; // 이미 방문한 노드를 다시 방문 => 사이클 존재
19
+ }
20
+ visited . add ( current ) ;
21
+ current = current . next ;
22
+ }
23
+
24
+ return false ; // 끝까지 갔다면 사이클 없음
25
+ } ;
26
+
27
+ // ### 2. Two Pointer 방식 (Floyd's Algorithm)
28
+ // - slow, fast 포인터 이용
29
+ // - 만날 경우 → 사이클 존재
30
+ // - 끝까지 도달 → 사이클 없음
31
+ // - 시간복잡도: O(n), 공간복잡도: O(1)
32
+
33
+ var hasCycle = function ( head ) {
34
+ let slow = head ;
35
+ let fast = head ;
36
+
37
+ while ( fast !== null && fast . next !== null ) {
38
+ slow = slow . next ; // 한 칸 이동
39
+ fast = fast . next . next ; // 두 칸 이동
40
+
41
+ if ( slow === fast ) {
42
+ return true ; // 만났다면 사이클 존재!
43
+ }
44
+ }
45
+
46
+ return false ; // 끝까지 갔다면 사이클 없음
47
+ } ;
You can’t perform that action at this time.
0 commit comments