Skip to content

Commit a27b490

Browse files
committed
Improve code comments for Linked list cycle
1 parent 8e6ce5e commit a27b490

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

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

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,24 @@
44
- -10^5 <= Node.val <= 10^5
55
- pos is -1 or a valid index in the linked-list
66
7-
Time Complexity:
8-
- Solution 1: O(n)
9-
- Solution 2: O(n)
10-
11-
Space Complexity:
12-
- Solution 1: O(n) - visited set์— ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ์Œ
13-
- Solution 2: O(1) - ์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
14-
15-
ํ’€์ด๋ฐฉ๋ฒ•:
16-
1. ์ฒ˜์Œ์—” ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐ, ํ•œ ๋ฒˆ ๋งˆ์ฃผ์นœ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋งŒ๋‚˜๋Š”์ง€๋ฅผ ์ฒดํฌํ•˜๋Š” ๋ฐฉ์‹
17-
2. slow, fast ๋‘ ๊ฐœ์˜ ๋…ธ๋“œ๋ฅผ ํ™œ์šฉ, ๋งŒ์•ฝ cycle์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ fast๊ฐ€ slow์™€ ์–ธ์  ๊ฐ€ ๋งŒ๋‚˜๊ฒŒ ๋จ,
18-
๋งŒ์•ฝ cycle์ด ์—†๋‹ค๋ฉด ๋‘˜์€ ๋งŒ๋‚˜์ง€ ์•Š์Œ
19-
"""
207
8+
<Solution 1>
9+
10+
Time Complexity: O(n)
11+
- while ๋ฃจํ”„๋ฅผ ์ตœ๋Œ€ n๋ฒˆ ์‹คํ–‰ (๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋งŒํผ)
12+
13+
Space Complexity: O(n)
14+
- visited set์— ์ตœ๋Œ€ n๊ฐœ์˜ ๋…ธ๋“œ ์ €์žฅํ•จ
15+
- set() ์กฐํšŒ/์‚ฝ์ž…์— O(1)
16+
17+
ํ’€์ด ๋ฐฉ๋ฒ•:
18+
- ํ•œ ๋ฒˆ ๋งˆ์ฃผ์นœ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋งŒ๋‚˜๋Š”์ง€๋ฅผ ์ฒดํฌํ•˜๋Š” ๋ฐฉ์‹
19+
"""
2120
# Definition for singly-linked list.
2221
# class ListNode:
2322
# def __init__(self, x):
2423
# self.val = x
2524
# self.next = None
26-
27-
# Solution 1: ํ•œ ๋ฒˆ ๋งˆ์ฃผ์นœ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋งŒ๋‚˜๋Š”์ง€๋ฅผ ์ฒดํฌ
2825
class Solution:
2926
def hasCycle(self, head: Optional[ListNode]) -> bool:
3027
visited = set()
@@ -38,14 +35,26 @@ def hasCycle(self, head: Optional[ListNode]) -> bool:
3835

3936
return False
4037

41-
# Solution 2: ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ ์ด์šฉ
38+
"""
39+
<Solution 2>
40+
41+
Time Complexity: O(n)
42+
- while ๋ฃจํ”„๋ฅผ ์ตœ๋Œ€ n๋ฒˆ ์‹คํ–‰ (๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋งŒํผ)
43+
44+
Space Complexity: O(1)
45+
- ํˆฌ ํฌ์ธํ„ฐ ์ด์™ธ์˜ ์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
46+
47+
ํ’€์ด ๋ฐฉ๋ฒ•:
48+
- ํˆฌ ํฌ์ธํ„ฐ ๋ฐฉ์‹ (slow, fast)
49+
- ๋งŒ์•ฝ cycle์ด ์žˆ๋‹ค๋ฉด, fast๊ฐ€ slow์™€ ์–ธ์  ๊ฐ€ ๋งŒ๋‚˜๊ฒŒ ๋จ
50+
- cycle์ด ์—†๋‹ค๋ฉด ๋‘˜์€ ๋งŒ๋‚˜์ง€ ์•Š์Œ
51+
"""
4252
class Solution:
4353
def hasCycle(self, head: Optional[ListNode]) -> bool:
4454
if not head:
4555
return False
4656

47-
slow = head
48-
fast = head
57+
slow = fast = head
4958

5059
while fast and fast.next:
5160
slow = slow.next
@@ -55,4 +64,3 @@ def hasCycle(self, head: Optional[ListNode]) -> bool:
5564
return True
5665

5766
return False
58-

0 commit comments

Comments
ย (0)