[LeetCode] 142. Linked List Cycle II java
来源:互联网 发布:手机视频剪辑拼接软件 编辑:程序博客网 时间:2024/04/30 16:41
/**142. Linked List Cycle II * @param head * @return */ public ListNode detectCycle(ListNode head) { if (head == null || head.next == null) { return null; } ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } } return null; } //让我们画个圈来解释这个问题,fast走的是a+b+c+b, // slow走的是a+b, 所以a=c, //相遇后一个从起点,一个从相遇点同时走,再次相遇,刚好走了a
从链表起始处到环入口长度为:a,从环入口到Faster和Slower相遇点长度为:x,整个环长为:c。
假设从开始到相遇,Slower走过的路程长为s,由于Faster的步速是Slower的2倍,那么Faster在这段时间走的路程长为2s。
而对于Faster来说,他走的路程还等于之前绕整个环跑的n圈的路程nc,加上最后这一次遇见Slower的路程s。
所以我们有:
2s = nc + s
对于Slower来说,他走的路程长度s还等于他从链表起始处到相遇点的距离,所以有:
s = a + x
通过以上两个式子代入化简有:
a + x = nc a = nc - x a = (n-1)c + c-x a = kc + (c-x)
那么可以看出,c-x,就是从相遇点继续走回到环入口的距离。上面整个式子可以看出,如果此时有个pointer1从起始点出发并且同时还有个pointer2从相遇点出发继续往前走(都只迈一步),那么绕过k圈以后, pointer2会和pointer1在环入口相遇。这样,换入口就找到了。
0 0
- [LeetCode] 142. Linked List Cycle II java
- [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] Linked List Cycle II (Java)
- leetcode:142. Linked List Cycle II(Java)解答
- [leetcode]142. Linked List Cycle II@Java解题报告
- 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
- 文章标题
- 关于程序员成长的一些思考
- java环境变量设置方法
- django安装报错error: [Errno 22] invalid mode ('wb') or filename:
- 课前测试
- [LeetCode] 142. Linked List Cycle II java
- 微服务技术栈
- 数理统计概念
- leetcode#224 Basic Calculator
- c++ 题目
- 1163 最高的奖励(贪心+优先队列)
- mvc后台校验 通过打标签的方式
- 项目测试问题总结
- [LeetCode] 143. Reorder List java