forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmike2ox.ts
39 lines (32 loc) ยท 946 Bytes
/
mike2ox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Source: https://leetcode.com/problems/linked-list-cycle/
* ํ์ด๋ฐฉ๋ฒ: Set์ ์ด์ฉํ์ฌ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ์ ์ฅํ๊ณ ์ํํ๋ฉด์ ์ค๋ณต๋ ๋
ธ๋๊ฐ ์๋์ง ํ์ธ
*
* ์๊ฐ๋ณต์ก๋: O(n)
* ๊ณต๊ฐ๋ณต์ก๋: O(n)
*/
// class ListNode {
// val: number;
// next: ListNode | null;
// constructor(val?: number, next?: ListNode | null) {
// this.val = val === undefined ? 0 : val;
// this.next = next === undefined ? null : next;
// }
// }
function hasCycle(head: ListNode | null): boolean {
if (head === null) return false;
// ๋ฐฉ๋ฌธํ ๋
ธ๋๋ค์ ์ ์ฅํ Set
const addr = new Set<ListNode>();
// ์ฒซ ๋
ธ๋ ์ถ๊ฐ
addr.add(head);
head = head.next;
// ๋ฆฌ์คํธ ์ํ
while (head !== null) {
// ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋์ธ ๊ฒฝ์ฐ cycle ์กด์ฌ
if (addr.has(head)) return true;
// ์๋ก์ด ๋
ธ๋ ์ถ๊ฐ
addr.add(head);
head = head.next;
}
return false;
}