Python solutions (dictionary and two pointers).


  • 0
    C
    # Utilize O(n) extra space
    def hasCycle(self, head):
        dic = {}
        while head:
            if head in dic:
                return True
            dic[head] = 0
            head = head.next
        return False
        
    # follow up: classic two poiters method
    def hasCycle1(self, head):
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next 
            slow = slow.next
            if slow is fast:
                return True
        return False

  • 0
    Z

    why not just use set?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.