Skip to content

Latest commit

 

History

History
75 lines (52 loc) · 1.38 KB

0141._linked_list_cycle.md

File metadata and controls

75 lines (52 loc) · 1.38 KB

141. Linked List Cycle

难度: Easy

刷题内容

原题连接

内容描述

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******

用个字典记录某个点是否被访问过,时间,空间复杂度都是O(n)

beats 96.59%

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head: 
            return False
        lookup = {}
        while head:
            if head in lookup:
                return True
            lookup[head] = 1
            head = head.next
        return False

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******

快慢指针, beats 96.59%

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