题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
题目解法
双指针
思路:
- 第一步确定链表中是否包含环,可用一个快指针,一个慢指针。快指针走两步,慢指针走一步,如果快指针能追上慢指针,说明链表有环。
- 第二步是如何找到环的入口,可以再初始化一个慢指针,新的慢指针从头开始遍历,旧的慢指针从快慢指针相交的节点开始遍历,两个慢指针再次相遇时即为入口节点。
PS:剑指Offer上要先算环内的节点数,其实没有必要。
时间复杂度
O
(
n
)
O(n)
O(n),空间复杂度
O
(
1
)
O(1)
O(1)。
class Solution(object):
def detectCycle(self, head):
if not head or not head.next: return None
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
slow2 = head
while slow != slow2:
slow = slow.next
slow2 = slow2.next
return slow
return None
辅助空间
Pythonic解法,代码简洁,但复杂度爆炸。
if…in 的时间复杂度
O
(
n
)
O(n)
O(n),总的时间复杂度
O
(
n
2
)
O(n^2)
O(n2),空间复杂度
O
(
n
)
O(n)
O(n)。
class Solution(object):
def detectCycle(self, head):
if not head or not head.next: return None
temp_list = []
while head:
if head in temp_list:
return head
temp_list.append(head)
head = head.next
return None