Skip to content

[river20s] WEEK 09 solutions #1533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 31, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions linked-list-cycle/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 주석보면서 알고리즘을 읽어보니 정말 술술 읽히네요..! 따로 검색해서 어떤 알고리즘인지 안찾아봐도 될 것 같습니다.

좋은습관 배워 갑니다! 감사합니다

# 플로이드 토끼와 거북이 알고리즘
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주석 설명이 기가막히네요;
일반적으로 플로이드 알고리즘 검색하면 너무 수학적이여서 난해했는데
토끼와 거북이에 비교하셔서 간단하게 설명하니 확실히 체감되었습니다.
문제 풀이 또한 정석적으로 진행해주셔서 너무 깔끔하네요!

# 느린 포인터와 빠른 포인터, 사이클이 있다면
# 느린 포인터를 빠른 포인터가 따라 잡아
# 언젠가 같은 노드에서 만나게 될 것
# TC: O(N)
# SC: O(1)
# 리스트가 비어 있거나 노드가 하나뿐이면 사이클 X
if not head or not head.next:
return False

slow = head # 느린 포인터
fast = head # 빠른 포인터

while fast is not None and fast.next is not None: # fast와 fast.next 모두 유효해야 fast.next.next 접근 가능
slow = slow.next # 느린 포인터 한 칸 이동
fast = fast.next.next # 빠른 포인터 한 칸 이동

if slow == fast: # 두 포인터가 만난다면
return True # 사이클 존재

# 루프가 끝났다면 포인터가 리스트 끝에 도달한 것이므로 사이클 X
return False