leetcode(142). Linked List Cycle II

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

  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指针辅助解出了问题。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值