Skip to content

Commit a87cf8a

Browse files
committed
solve 1
1 parent b122b9d commit a87cf8a

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

โ€Žlinked-list-cycle/pmjuu.pyโ€Ž

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'''
2+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
3+
- `fast`์™€ `slow` ํฌ์ธํ„ฐ๊ฐ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜๋ฉด์„œ ์ฃผ์–ด์ง„ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด์— ๋น„๋ก€ํ•˜๋Š” ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.
4+
- ๋”ฐ๋ผ์„œ ์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•˜๊ฒŒ ๋˜๋ฏ€๋กœ O(n)์ž…๋‹ˆ๋‹ค.
5+
6+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
7+
- ์ถ”๊ฐ€์ ์ธ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , `fast`์™€ `slow`๋ผ๋Š” ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ O(1)์ž…๋‹ˆ๋‹ค.
8+
'''
9+
from typing import Optional
10+
# Definition for singly-linked list.
11+
class ListNode:
12+
def __init__(self, x):
13+
self.val = x
14+
self.next = None
15+
16+
class Solution:
17+
def hasCycle(self, head: Optional[ListNode]) -> bool:
18+
fast = head
19+
slow = head
20+
21+
while fast and fast.next:
22+
fast = fast.next.next
23+
slow = slow.next
24+
25+
if fast == slow:
26+
return True
27+
28+
return False

0 commit comments

Comments
ย (0)