直接法:
原本想法是用list存里面的链表的表头的数字的,结果发现如果给的链表如果数字有相同的话就会不行,于是还是要存链表才行,这样比较费空间
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
p = head
rec = []
count = 0
while p != None:
if p in rec:
return True
else:
rec.append(p)
p = p.next
return False
用set来优化
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
target = {head}
#set中记录的是该节点(是一个对象,有独立的内存地址,即使.val一样如果不是同一个位置,那也是不同的,能存在set中)
head =head.next
while head:
if head in target:
return True
else:
target.add(head)
head = head.next
return False
第三种就是快慢指针
可以理解成博尔特和你在环形赛道上跑步,博尔特跑步的速度是你的两倍,他跑一步等于你跑两步,这样博尔特迟早能追上你。
如果是一条直线的赛道,博尔特则会先比你到达终点。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast,slow = head,head
while fast and fast.next:
fast,slow = fast.next.next,slow.next
if fast == slow:
return True
return False