Skip to content

Commit 024f8d3

Browse files
committed
linked-list-cycle solution
1 parent 284e10e commit 024f8d3

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

โ€Žlinked-list-cycle/jdy8739.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff 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์„ ์‚ฌ์šฉํ•˜๊ธฐ๋•Œ๋ฌธ์— (๊ฑฐ๋ถ์ด์™€ ํ† ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์šฉ)

0 commit comments

Comments
ย (0)