LeetCode题解:Linked List Cycle II
来源:互联网 发布:淘宝客新建导购推广 编辑:程序博客网 时间:2024/06/06 03:57
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?
题意:给定链表,返回环的起点;若不存在起点,返回null。要求:O(1)空间
思路:快慢指针,只是要注意一个小细节帮助我们找到起点:假如指针能够相遇,则必有快指针的总路程减去慢指针的总路程等于环长度的倍数,否则是不可能相遇的。
那么假设到达相遇点时慢指针走的步数为t,则有2t-t=n*l,其中n代表绕环的次数,[0,…),l表示环的长度。
现在假设从环起点到相遇点的距离为m,此时有:
从相遇点到环起点的距离为m’=l-m,从起点到环起点的距离为r=t-m,即m=t-r。所以m’=l-t+r=(1-n)*l+r,即r=m’+(n-1)l。也就是说r和m’是相等的。利用这个性质就可以找到起点了
代码:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */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 II题解
- [题解][LeetCode][Linked List Cycle II]
- LeetCode题解:Linked List Cycle II
- Leetcode题解 142. Linked List Cycle II
- leetcode题解-142. Linked List Cycle II
- leetcode题解-142. Linked List Cycle II
- LeetCode 题解(144): Linked List Cycle II
- LeetCode题解——Linked List Cycle II
- LeetCode题解:Linked List Cycle
- [题解][LeetCode][Linked List Cycle]
- LeetCode题解:Linked List Cycle
- LeetCode题解:Linked List Cycle
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- 1016. 部分A+B
- BZOJ 1112 POI2008 砖块
- 6.2、朴素贝叶斯实例
- 51Nod 1049 最大子段和(简单DP)
- java concurrent之BlockingQueue
- LeetCode题解:Linked List Cycle II
- Cobbler Quickstart Guide
- 6.3、朴素贝叶斯之垃圾邮件过滤
- xendesttop添加xenserver测试小记
- 7、KNN(K近邻)
- KK's Number
- c#之异常之线程访问控件
- java
- UIButton 字体居左