Saturday, February 23, 2019

LeetCode 142. Linked List Cycle II

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#use list, 1172ms
class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None       
        else:
            nodes = []
            while True:
                if not head in nodes:
                    nodes.append(head)
                    head = head.next
                    if not head: return None
                else:
                    return head

#use dictionary (hash-table), 40ms
class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None       
        else:
            nodes = {}
            while True:
                if not head in nodes:
                    nodes[head] = None
                    head = head.next
                    if not head: return None
                else:
                    return head

No comments:

Post a Comment