leetcode(142). Linked List Cycle II

xiaoxiao2021-02-28  96

problem

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up: Can you solve it without using extra space?

solution

使用set来检测节点是否重复出现,空间复杂度为 O(n)

# 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 """ s = set() while head: if head in s: return head else: s.add(head) head = head.next return None

without extra space

这个解法对之前的leetcode(141). Linked List Cycle做一些修改,如果有环那么设

L1为链表起点与环起点的距离,L2为环起点与相遇节点的距离C为环的长度

我们可以知道: 1. 相遇时step1走过的长度为L1+L2 2. step2走过的长度为L1+L2+n*C 3. 由于step2走过的距离是step1的2倍,所以有   2 * (L1+L2) = L1 + L2 + n * C => L1 + L2 = n * C => L1 = (n - 1) C + (C - L2)

所以链表起点与环起点的距离等于相遇节点与环起点的距离,所以等step1和step2相遇的时候,我们新建一个指针entry指向链表头结点,然后step1和entry同时前进,当他们相遇的时候指向的就是环的起始位置。

class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return None step1 = head step2 = head entry = head while step2.next is not None and step2.next.next is not None: step1 = step1.next step2 = step2.next.next if step1 is step2: while step1 is not entry: step1 = step1.next entry = entry.next return entry return None

总结

因为链表里面有一个环,所以直接求出环的起始位置需要考虑模的问题,并不简单,所以上面的解法对等式进行变形,使用一个entry指针辅助解出了问题。

再遇到这样复杂的问题时也可以这样,定义变量,列出已知等式,对等式进行变形,转化问题。

转载请注明原文地址: https://www.6miu.com/read-64198.html

最新回复(0)