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)