[Leetcode] 142. Linked List Cycle II 解题报告
来源:互联网 发布:matlab算法工具箱 编辑:程序博客网 时间:2024/04/29 17:53
题目:
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?
思路:
在Leetcode 141的基础上,我们来推导一下怎么确定环的入口。假设有环,那么慢指针最多走n步(即回到头部)就会和快指针相遇。以盗的图为例,假如从链表头部到环入口的长度为k(即D的位置),快慢指针相遇在E,从相遇的节点到环入口的长度为y。在相遇的时候快指针多走了一圈环行,那么快慢指针到相遇的时候各走的步数是:
slow = k + x;
fast = k + x + y + x.
因为快指针速度比慢指针快一倍,因此会有如下关系:fast = 2 * slow,即:(k + x + y + x) = 2 * (k + x),可以得出k = y。因此现在从快慢指针相遇的地方到环入口和从链表头部到环入口的距离相等。所以让快慢指针以相同的速度从这两个地方再开始走,到相遇的地方就是即为环的入口(本题的分析部分参考了小榕流光的博客:http://blog.csdn.net/qq508618087/article/details/50473996)。算法的时间复杂度仍然是O(n),空间复杂度O(1)。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { if (head == NULL) { return NULL; } ListNode *slow = head, *fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { fast = head; while (fast != slow) { fast = fast->next; slow = slow->next; } return slow; } } return NULL; }};
0 0
- [leetcode] 142. Linked List Cycle II 解题报告
- [Leetcode] 142. Linked List Cycle II 解题报告
- [leetcode]142. Linked List Cycle II@Java解题报告
- LeetCode — Linked List Cycle II 解题报告
- [LeetCode OJ] Linked List Cycle II 解题报告
- LeetCode---Linked List Cycle、Linked List Cycle II解题分析
- LeetCode — Linked List Cycle 解题报告
- [LeetCode OJ] Linked List Cycle 解题报告
- [leetcode] 141. Linked List Cycle 解题报告
- 【LeetCode】Linked List Cycle 解题报告
- [Leetcode] 141. Linked List Cycle 解题报告
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- [LeetCode]Reverse Linked List II, 解题报告
- [LeetCode]Reverse Linked List II解题报告
- 【LeetCode】Reverse Linked List II 解题报告
- [LeetCode] Reverse Linked List II 解题报告
- 高盛想要做华尔街的谷歌
- 我是Papi酱,一个集才华与美貌于一身的过气网红
- 什么场景应该用 MongoDB ?
- Java基础--基本数据类型(浮点类型)
- Together项目IOS平台开发01
- [Leetcode] 142. Linked List Cycle II 解题报告
- Android 事件分发机制(通过源码解析,附带记忆图)
- mysql(二)
- MFC中更改程序显示图标
- codedev-1229数字游戏
- 一些常用的html5特性
- sublime的QuickXDev插件不能runwithplayer或无法准确定位跳转查看源码
- 35 个 Java 代码性能优化总结
- 专访知乎张伟:RFC技术评审机制如何助力知乎实现工程文化落地