# 141. Linked List Cycle #### Difficulty: Easy link: https://leetcode.com/problems/linked-list-cycle/ ### 1. Hash table #### $O(n)$ runtime, $O(n)$ space 用set紀錄看過的node,如果有重複就代表有cycle。 ##### python ```python= # 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: visit = set() while head is not None: if head in visit: return True visit.add(head) head = head.next return False ``` ### 2. Two Pointers #### $O(n)$ runtime, $O(1)$ space Floyd Cycle Detection Algorithm (龜兔賽跑演算法),用一快一慢的兩個指標,如果快的指標會追到慢的指標,就代表有cycle。 ##### python ```python= # 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 while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow is fast: return True return False ``` ###### tags: `leetcode`