728x90
난이도 : medium
linked list의 cycle이 시작하는 지점을 return하는 문제.
cycle이 없으면 null return
보통 linked list에서 cycle에 관련된 문제는, Floyd's Tortoise and Hare 알고리즘을 사용하여 cycle이 있는지 확인한다.
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next: #Floyd's Tortoise and Hare 알고리즘
slow = slow.next
fast = fast.next.next
if slow == fast: # 두 pointer가 만나면, cycle이 있다는 의미
break
if not fast or not fast.next: #fast나 fast의 뒤가 없다 :cycle이 없음
return None
slow = head
while slow != fast: #두 pointer가 같은 속도로 이동할 때 만나는 지점이 cycle의 시작점
slow = slow.next
fast = fast.next
return slow
- Floyd's Tortoise and Hare 알고리즘을 사용하여, slow와 fast가 만나는지 확인
- fast가 없거나, fast.next가 없다면 tail이 있다는 것. cycle이 없으니까 None을 return
- slow를 head로 다시 설정 후, 두 pointer를 한 칸씩 움직이다 보면 만나는 지점이 cycle의 시작점이다.
- 그 때의 slow를 return
Runtime : 45ms (65.69%)
Memory : 19.70MB (50.76%)
728x90
'코딩 공부 > Leetcode' 카테고리의 다른 글
[Python] 19. Remove Nth Node From End of List (0) | 2025.02.10 |
---|---|
[Python] 160. Intersection of Two Linked Lists (0) | 2025.02.09 |
[Python] 977. Squares of a Sorted Array (0) | 2025.02.07 |
[Python] 1726. Tuple with Same Product (0) | 2025.02.06 |
[Python] 3151. Special Array I (0) | 2025.02.06 |