LeetCode 142. Linked List Cycle II
来源:互联网 发布:大陆网络用语在台湾火 编辑:程序博客网 时间:2024/05/21 12:47
题目:[leetcode-142]
思路
寻找环的入口,需要做如下的数学证明。先给出示意图如下:
做如下假设:
- 设直线段的端点为
X点 - 环的入口点为
Y点 - 快慢指针相遇的点为
Z点 - 其中,有
XY−→−=l,YZ−→−=r0ZY−→−=c,
当快慢指针相遇时,有下面的式子:
由于快指针走过的路程是慢指针的两倍,所以有:
整理得:
即
所以,相遇点到入口的距离加上(k-1)个环等于端点到入口的距离。
所以,分别设两个指针从端点和相遇点开始移动,当他们相遇时,即为环的入口。
public class LeetCode142 { public ListNode detectCycle(ListNode head) { // 利用快慢指针找相遇点 ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast) break; } if(fast == null || fast.next == null) return null; //slow指针从头指针出发,fast指针从相遇点出发 slow = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return slow; }}
0 0
- [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
- 142. Linked List Cycle II leetcode list
- 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 @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- 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#笔记整理(六)
- Naive Bayes 朴素贝叶斯算法
- 算法导论读书笔记(12)
- svm 问题整理
- windows64位Python3.5.2基础上,安装numpy、matplotlib、scipy(whl文件)安装tensorflow及sklearn包
- LeetCode 142. Linked List Cycle II
- C#基础知识之冒泡,选择排序法
- 算法导论读书笔记(13)
- apache的keepalive和keepalivetimeout(apache优化)
- 怎样防止微信公众号被举报投诉后被封
- 剑指offer-矩形覆盖
- CSDN日报20170311——《程序员每天累成狗,是为了什么》
- 提高对C++的认识
- pat-a1097. Deduplication on a Linked List (25)