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来检测节点是否重复出现,空间复杂度为
# 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做一些修改,如果有环那么设
- 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指针辅助解出了问题。
再遇到这样复杂的问题时也可以这样,定义变量,列出已知等式,对等式进行变形,转化问题。
阅读全文
0 0
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- LeetCode 142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- [leetcode 142]Linked List Cycle II
- Leetcode NO.142 Linked List Cycle II
- [leetcode]142 Linked List Cycle II
- [LeetCode 142]Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- [Leetcode 142] Linked List Cycle II
- [leetcode-142]Linked List Cycle II(c)
- leetcode 142: Linked List Cycle II
- leetCode #142 Linked List Cycle II
- Leetcode #142 Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- 【LEETCODE】142-Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- HDU 6069 Counting Divisors(数学)
- UNIX操作系统和Linux操作系统介绍
- MainActivity(周考1)
- 【JVM】JVM系列
- 微博发布页面
- leetcode(142). Linked List Cycle II
- 进程和线程的区别及线程的介绍
- 布隆过滤器
- MyAdapter(周考1)
- java 泛型
- 重磅 | 2017 开发者生态报告,学什么语言最有前途
- 《Unix网络编程》卷1:套接字联网API(第3版):基本TCP编程、TCP客户端/服务器程序、I/O复用
- LaTeX使用小结
- MyFragemt(周考1)