LeetCode-Linked List Cycle
来源:互联网 发布:安卓游戏开发知乎 编辑:程序博客网 时间:2024/05/15 14:41
寻找链表是否有环
方法是快慢指针
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c
slow肯定没有走够超过一圈,在第一圈的中间停下来。假设直接就在圆上,则必定slow走一圈相遇,若前面还有一截,则不必等到一圈即可相遇。同时起步是最远的距离。
public class Solution { 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 = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return fast; } }
阅读全文
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- python字符串的方法及注释
- SASS简介及安装
- mysql中在user表中插入一个root用户
- java await、wait与sleep和yield之间的区别
- fabric源码解析14——peer的gossip服务之初始化
- LeetCode-Linked List Cycle
- 找出一个数组中只出现一次的两个数
- 堆的创建
- 【GDOI2017模拟9.21】妮厨的愤怒
- 线程(4)--yield方法
- Leetcode #12. Integer to Roman & #13. Roman to Integer
- C#基础-048 Const和ReadOnly
- OpenGL ES之glUniform函数
- c# .Net 微信扫码支付模式二 开发时遇到的“签名错误”问题