LeetCode 142 Linked List Cycle II
来源:互联网 发布:广联达软件安装教程 编辑:程序博客网 时间:2024/06/03 19:32
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?
具体过程及证明见:代码过程证明
另外再附加一段:F可能超了S很多圈的:假设刚进环的时候慢指针走了m步,环的大小为n,快慢指针在距离环起点x步的时候相遇。慢指针是一定走不完一圈就会和快指针相遇的(因为最惨的情况下就是慢指针进圈的时候快指针在它前面一个,快指针速度时慢的两倍,这种悲剧情况下慢指针也不可能走完一圈就会被追到)。这是慢指针走了m+x步,快指针走了2(m+x)步,快指针在圈内走了2(m+x)-m=m+2x步。由于相遇在x位置,所以 m+2x % n = x,推出m+2x = i * n + x,于是m+x = i*n。我们注意到慢指针已经走了x步了,再走m步时一定会回到圈的起点的(m+x = i*n),所以等它们相遇后,一个指针从head开始走,然后慢指针从相遇的位置出发,则一定会相遇到圈的起点。
public ListNode detectCycle(ListNode head) {if (head == null || head.next == null) return null;ListNode slow = head,fast = head;while (slow != null && fast != null && fast.next != null) {fast = fast.next.next;slow = slow.next;if (fast == slow) {fast=head;while (fast!=slow) {fast= fast.next;slow = slow.next;}return fast;}}return null;}
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
- 获取唯一UUID/UDID的方案
- java 函数式接口(FuncationalInterface)
- 【转载】入门必看-嵌入式开发的学习方法
- 浅谈算法和数据结构: 七 二叉查找树
- Android 主流网络请求框架 Android-async-http
- LeetCode 142 Linked List Cycle II
- 微信支付异步回调的坑,调用成功了回调地址却没有数据
- ios 内置支付宝
- hdu3833 YY's new problem--哈希表
- ffmpeg arm编译
- inline函数详解
- ireport、jasperreport studio 导出excel有白色背景
- JavaScript交互篇
- 数据库学习整理