leetcode(142). Linked List Cycle II

来源:互联网 发布:sql 注入 1 1 编辑:程序博客网 时间:2024/06/14 10:10

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 = Noneclass 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做一些修改,如果有环那么设

  1. L1为链表起点与环起点的距离,
  2. L2为环起点与相遇节点的距离
  3. 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指针辅助解出了问题。

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

原创粉丝点击