Leetcode | Linked List Cycle (判断链表是否存在环)

Description:

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.

Example:

Leetcode | Linked List Cycle (判断链表是否存在环)_第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).

Leetcode | Linked List Cycle (判断链表是否存在环)_第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.

Ideas:

	In order to judge whether there is a cycle in the linked list, first idea is to traverse the list, 
if a elem'address appears twice, This linked list exists a cycle. In the worst case, time complexity 
and space complexity both are O(n).
	The official way reminds using a slow pointer and a fast pointer to traverse list respectively.If the 
fast one catch up with the slow one, it proves hypothesis is true. 

Code:

def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        seen = dict()
        while head:
            if seen.get(head):
                return True
            seen[head] = 1
            head = head.next
        return False

Execution time:36ms
Memory consumption:20MB

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        
        slow = head
        fast = head.next

        while slow != fast:
            if not fast or not fast.next:
                return False
            slow = slow.next
            fast = fast.next.next
        
        return True

Execution time:44ms
Memory consumption:19MB

summary

	"The Tortoise and the Hare algorithm" Get√

你可能感兴趣的:(Leetcode)