题目描述:
思考:
建立一个list,存储节点,出现重复,就返回。
class Solution:
def EntryNodeOfLoop(self, pHead):
if pHead is None or pHead.next is None:
return None
mem = []
while pHead not in mem:
mem.append(pHead)
pHead = pHead.next
if pHead is None:
return None
else:
return pHead
答案:
答案用的是set()
,占用内存比list少了很多很多;以后记得多用set,它不允许重复
上述答案需要的空间复杂度为
O
(
n
)
O(n)
O(n),还要一种答案是双指针,空间复杂度为
O
(
1
)
O(1)
O(1)
要解方程呢~
假设环外长度为a,环内长度为b;快指针一次移两格,慢指针一次移一格;
- 快指针走到入口处满足: f a s t = a + n ∗ b fast =a+n*b fast=a+n∗b;
- 快慢指针一定会在环内相遇,此时 f a s t − s l o w = n ∗ b fast-slow=n*b fast−slow=n∗b;又因为 f a s t = 2 ∗ s l o w fast=2*slow fast=2∗slow,代入一下,相遇时 s l o w = n ∗ b slow=n*b slow=n∗b
- 相遇后,让fast回到头结点,慢指针继续走,当二者再次相遇时,就是头结点了; s l o w = n ∗ b + a slow=n*b+a slow=n∗b+a,刚好会和快节点在入口相遇呢。
看了好一会儿才看明白,这也太巧妙了吧
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
slow = pHead
fast = pHead
while fast !=None and fast.next !=None:
fast = fast.next.next
slow = slow.next
if slow == fast:
while pHead != slow:
pHead =pHead.next
slow = slow.next
return slow
return None