문제
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again
by continuously following the next pointer.
Internally, pos is used to denote the index of the node that tail's next pointer is connected to.
Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list.
Otherwise, return false.
헤드 노드가 주어졌을때 리스트에
순열 사이클이 있다면 False! 없으면 True!
https://leetcode.com/problems/linked-list-cycle/description/
예시
예시 1
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
예시 2
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
예시 3
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
풀이
Floyd's Tortoise and Hare / 플로이드의 토끼와 거북이
알고리즘을 사용하면 바로 풀 수 있는 문제
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head # 안녕 난 거북이, 토끼
while fast and fast.next != None: # 토끼가 결승점 못찾으면
slow = slow.next # 거북이는 점점 따라잡고
fast = fast.next.next # 토끼는 돌고 돌다가
if slow == fast: # 거북이한테 잡힌다
return True # 찾았네!
return False # 토끼 어디감 주륵
반응형
'알고리즘 & 자료구조 > Leetcode' 카테고리의 다른 글
[Leetcode 146] - LRU Cache w/ Python (0) | 2024.04.07 |
---|---|
[Leetcode 287] - Find the Duplicate Number w/ Python (1) | 2024.04.07 |
[Leetcode 2] - Add Two Numbers w/ Python (0) | 2024.04.07 |
[Leetcode 138] - Copy List with Random Pointer w/ Python (1) | 2024.04.06 |
[Leetcode 206] - Reverse Linked List w/ Python (0) | 2024.04.06 |