难度: 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