File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -33,3 +33,71 @@ var hasCycle = function (head) {
3333
3434// 시간복잡도 O(n) -> 최대 리스트의 노드 수 만큼 while문이 반복되므로
3535// 공간복잡도 O(n) -> set에 최대 리스트의 노드 수 만큼 size가 증가되므로
36+
37+
38+ /**
39+ * Definition for singly-linked list.
40+ * function ListNode(val) {
41+ * this.val = val;
42+ * this.next = null;
43+ * }
44+ */
45+
46+ /**
47+ * @param {ListNode } head
48+ * @return {boolean }
49+ */
50+ var hasCycle = function ( head ) {
51+ if ( ! head ?. next ) {
52+ return false ;
53+ }
54+
55+ let turtle = head ;
56+ let rabbit = head ;
57+
58+ while ( turtle . next && rabbit . next ) {
59+ if ( turtle === rabbit ) {
60+ return true ;
61+ }
62+
63+ turtle = turtle . next ;
64+ rabbit = rabbit . next . next ;
65+ }
66+
67+ return false ;
68+ } ;
69+
70+ /**
71+ * Definition for singly-linked list.
72+ * function ListNode(val) {
73+ * this.val = val;
74+ * this.next = null;
75+ * }
76+ */
77+
78+ /**
79+ * @param {ListNode } head
80+ * @return {boolean }
81+ */
82+ var hasCycle = function ( head ) {
83+ if ( ! head ?. next || ! head ?. next . next ) {
84+ return false ;
85+ }
86+
87+ let turtle = head ;
88+ let rabbit = head ;
89+
90+ while ( turtle && rabbit ?. next ) {
91+ turtle = turtle . next ;
92+ rabbit = rabbit . next . next ;
93+
94+ if ( turtle === rabbit ) {
95+ return true ;
96+ }
97+ }
98+
99+ return false ;
100+ } ;
101+
102+ // 시간복잡도 O(n) -> 최대 리스트의 노드 수 만큼 while문이 반복되므로
103+ // 공간복잡도 O(1) -> 고정된 두 변수 turtle, rabbit을 사용하기때문에 (거북이와 토끼 알고리즘 사용)
You can’t perform that action at this time.
0 commit comments