hahh.so young so naive 的我居然想用这种弱智方法破这题。。。
编译不通过啊 因为实例对象不能酱紫比较的。python它不知道咋比啊需要另外写函数操作实现这个。(but据说可以比node存放的内存啊blabla。 暂缓吧我先把这个错误的二逼算法po上来~
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
nodes = []
this = head
while (this.next is not None):
if this in nodes:// so young so naive :)
return this
else:
nodes.append(this)
this = this.next
return None
。看答案都看了半天才看懂(⊙﹏⊙)
自己写下数学推导吧>>(快慢指针同141题
s: list起点到循环起点的距离
m:list起点到快慢指针相遇点的距离
k:慢指针到相遇时走的距离(快指针是2k
r:循环的长度
然后快慢指针相遇时快指针追了慢指针nr的距离所以①2k-k = nr (第一次相遇时追了r,第二次相遇追了2r....((n是指第n次相遇
由①得出 ②k=nr
由距离关系得出③ s = k-m
将②代入③得出④s = nr-m = (n-1)r+(r-m)
我们取n=1(即计算第一次相遇时的各参数)代入④。得到⑤s=r-m
那么从起点起走s 步就可以到循环的起点。
所以一个point从起点开始走。另一个point从快慢指针相遇点开始走。一步一步走。
r-m步之后两个point都会到循环的起点。(此时另一个point走了正好r-m步。 循环长度为r 而它开始时已经走过了m步。
所以两个point相遇时返回那个地点就好了~
以上~ 附代码如下。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if (head is None) or (head.next is None):
return None
fast = head
slow = head
while (fast is not None)and(fast.next is not None) :
fast = fast.next.next
slow = slow.next
if fast==slow:
p1 = head
p2 = fast
while p1!=p2:
p1 = p1.next
p2 = p2.next
return p1
return None