Skip to content

Commit 85687e8

Browse files
committed
solve: Linked List Cycle
1 parent a320671 commit 85687e8

File tree

1 file changed

+51
-6
lines changed

1 file changed

+51
-6
lines changed

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

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,58 @@
11
"""
22
Constraints:
3-
-
3+
- The number of the nodes in the list is in the range [0, 10^4]
4+
- -10^5 <= Node.val <= 10^5
5+
- pos is -1 or a valid index in the linked-list
46
5-
Time Complexity:
6-
-
7+
Time Complexity:
8+
- Solution 1: O(n)
9+
- Solution 2: O(n)
710
8-
Space Complexity:
9-
-
11+
Space Complexity:
12+
- Solution 1: O(n) - visited set์— ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ์Œ
13+
- Solution 2: O(1) - ์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
1014
1115
ํ’€์ด๋ฐฉ๋ฒ•:
12-
1.
16+
1. ์ฒ˜์Œ์—” ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐ, ํ•œ ๋ฒˆ ๋งˆ์ฃผ์นœ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋งŒ๋‚˜๋Š”์ง€๋ฅผ ์ฒดํฌํ•˜๋Š” ๋ฐฉ์‹
17+
2. slow, fast ๋‘ ๊ฐœ์˜ ๋…ธ๋“œ๋ฅผ ํ™œ์šฉ, ๋งŒ์•ฝ cycle์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ fast๊ฐ€ slow์™€ ์–ธ์  ๊ฐ€ ๋งŒ๋‚˜๊ฒŒ ๋จ,
18+
๋งŒ์•ฝ cycle์ด ์—†๋‹ค๋ฉด ๋‘˜์€ ๋งŒ๋‚˜์ง€ ์•Š์Œ
1319
"""
20+
21+
# Definition for singly-linked list.
22+
# class ListNode:
23+
# def __init__(self, x):
24+
# self.val = x
25+
# self.next = None
26+
27+
# Solution 1: ํ•œ ๋ฒˆ ๋งˆ์ฃผ์นœ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋งŒ๋‚˜๋Š”์ง€๋ฅผ ์ฒดํฌ
28+
class Solution:
29+
def hasCycle(self, head: Optional[ListNode]) -> bool:
30+
visited = set()
31+
32+
current = head
33+
while current:
34+
if current in visited:
35+
return True
36+
visited.add(current)
37+
current = current.next
38+
39+
return False
40+
41+
# Solution 2: ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ ์ด์šฉ
42+
class Solution:
43+
def hasCycle(self, head: Optional[ListNode]) -> bool:
44+
if not head:
45+
return False
46+
47+
slow = head
48+
fast = head
49+
50+
while fast and fast.next:
51+
slow = slow.next
52+
fast = fast.next.next
53+
54+
if slow == fast:
55+
return True
56+
57+
return False
58+

0 commit comments

Comments
ย (0)