File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode {
2
+ val : number ;
3
+ next : ListNode | null ;
4
+ constructor ( val ?: number , next ?: ListNode | null ) {
5
+ this . val = val === undefined ? 0 : val ;
6
+ this . next = next === undefined ? null : next ;
7
+ }
8
+ }
9
+
10
+ /**
11
+ * @link https://leetcode.com/problems/linked-list-cycle/description/
12
+ *
13
+ * 접근 방법 :
14
+ * - 노드 순회하면서 방문한 노드에 저장
15
+ * - 방문할 노드가 이미 방문한 노드에 있으면 순환 구조 이므로 true 리턴
16
+ *
17
+ * 시간복잡도 : O(n)
18
+ * - 순환 이전 노드의 개수 n만큼 순회하면서 순환 여부 확인
19
+ *
20
+ * 공간복잡도 : O(n)
21
+ * - visited set에 순환되기 이전 노드 n개 저장
22
+ */
23
+ function hasCycle ( head : ListNode | null ) : boolean {
24
+ const visited = new Set < ListNode > ( ) ;
25
+ let current = head ;
26
+
27
+ while ( current !== null ) {
28
+ if ( visited . has ( current ) ) return true ;
29
+
30
+ visited . add ( current ) ;
31
+ current = current . next ;
32
+ }
33
+
34
+ return false ;
35
+ }
36
+
37
+ /*
38
+ * 접근 방법 :
39
+ * - 공간복잡도 O(1)로 풀이
40
+ * - 사이클이 있으면 두 포인터가 결국 같은 노드를 가리키게 되므로 투 포인터 사용
41
+ * - 사이클이 없는 경우를 위해서 tail노드의 null체크를 해야함
42
+ *
43
+ * 공간복잡도 : O(1)
44
+ * - 추가 메모리없이 slow, fast 포인터만 사용하므로 O(1)
45
+ */
46
+ function hasCycle ( head : ListNode | null ) : boolean {
47
+ let slow = head ;
48
+ let fast = head ;
49
+
50
+ while ( fast !== null && fast . next !== null ) {
51
+ slow = slow . next ;
52
+ fast = fast . next . next ;
53
+
54
+ if ( slow === fast ) return true ;
55
+ }
56
+
57
+ return false ;
58
+ }
You can’t perform that action at this time.
0 commit comments