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