File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Optional
2
+
3
+
4
+ # Definition for singly-linked list.
5
+ class ListNode :
6
+ def __init__ (self , x : int ) -> None :
7
+ self .val = x
8
+ self .next = None
9
+
10
+
11
+ class Solution :
12
+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
13
+ """
14
+ - Idea: ์ฌ์ดํด์ด ์๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ธ์ง ํ๋จํ๊ธฐ ์ํด ๋ ๊ฐ์ ํฌ์ธํฐ, slow์ fast๋ฅผ ์ฌ์ฉํ๋ค.
15
+ slow ํฌ์ธํฐ๋ ํ๋ฒ์ ํ ์นธ์ฉ, fast ํฌ์ธํฐ๋ ํ๋ฒ์ ๋ ์นธ์ฉ ์ด๋ํ๋ค.
16
+ ๋ง์ฝ ๋ ํฌ์ธํฐ๊ฐ ๋ง๋๋ฉด, ๋ฆฌ์คํธ์ ์ฌ์ดํด์ด ์กด์ฌํ๋ค๊ณ ํ๋จํ ์ ์๋ค.
17
+ fast๊ฐ ๋ฆฌ์คํธ์ ๋์ ๋๋ฌํ๋ค๋ฉด ์ฌ์ดํด์ด ์๋ค๊ณ ํ๋จํ๋ค.
18
+ - Time Complexity: O(n). n์ ๋ฆฌ์คํธ์ ํฌํจ๋ ๋
ธ๋์ ๊ฐ์๋ค.
19
+ ์ฌ์ดํด์ด ์๋ ๊ฒฝ์ฐ, fast ํฌ์ธํฐ๋ ๋ฆฌ์คํธ ๋๊น์ง ์ด๋ํ๋ค.
20
+ ์ฌ์ดํด์ด ์๋ ๊ฒฝ์ฐ, ๋ ํฌ์ธํฐ๊ฐ ๋ง๋ ๋๊น์ง ์ด๋ํ๋ฏ๋ก O(n)์ ์๊ฐ์ด ์์๋๋ค.
21
+ - Space Complexity: O(1). ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ํฌ๊ธฐ์ ์๊ด์์ด slow์ fast ๋ณ์๋ง ์ฌ์ฉ๋๋ฏ๋ก
22
+ ์์ ๊ณต๊ฐ๋ง ์ฐจ์งํ๋ค.
23
+ """
24
+ slow , fast = head , head
25
+
26
+ while fast and fast .next :
27
+ slow = slow .next
28
+ fast = fast .next .next
29
+
30
+ if slow == fast :
31
+ return True
32
+
33
+ return False
You canโt perform that action at this time.
0 commit comments