728x90
난이도 : easy
head라는 linked list에서 cycle을 구성한다면 True를 return하는 문제
# 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:
slow, fast = head, head
while slow != None and fast != None:
slow = slow.next
if slow == None:
return False
fast = fast.next
if fast == None:
return False
fast = fast.next
if slow == fast:
return True
return False
- slow, fast 포인터를 모두 head로 초기화
- 리스트의 끝에 도달할 때까지 반복
- slow는 한 칸씩, fast는 두 칸씩 이동하고, 위치가 리스트의 끝인지 확인
- slow와 fast가 만나면, 순환되는 중이기 때문에 True return
- 순환이 없는 경우 False return
Runtime : 47ms (63.07%)
Memory : 19.87MB (47.52%)
728x90
'코딩 공부 > Leetcode' 카테고리의 다른 글
[Python] 1726. Tuple with Same Product (0) | 2025.02.06 |
---|---|
[Python] 3151. Special Array I (0) | 2025.02.06 |
[Python] 707. Design Linked List (0) | 2025.02.04 |
[Python] 1800. Maximum Ascending Subarray Sum (0) | 2025.02.04 |
[Python] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (0) | 2025.02.03 |