Saturday, August 22, 2015

Leetcode 142. Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/

This needs some math calculation, while the result turns out to be simple enough. Still slow and fast pointers.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param head, a ListNode
    # @return a list node
    def detectCycle(self, head):
        fast, slow = head, head
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
            if fast is slow:
                fast = head
                while fast is not slow:
                    fast, slow = fast.next, slow.next
                return fast
        return None
Run Time: 80 ms

No comments:

Post a Comment