第10题 Linked List Cycle II
来源:互联网 发布:电脑淘宝店招尺寸 编辑:程序博客网 时间:2024/06/07 23:43
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Solution:
/** * 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) { if(head==null) return null; ListNode ptr1=head, ptr2=head; while(ptr1!=null && ptr2!=null){ if(ptr1.next==null || ptr2.next==null || ptr2.next.next==null) return null; ptr1=ptr1.next; ptr2=ptr2.next.next; if(ptr1==ptr2) break; } ptr1=head; while(ptr1!=ptr2){ ptr1=ptr1.next; ptr2=ptr2.next; } return ptr1; }}
设圈前长度为x, 两指针在圈中相遇位置为k,圈周长为r。设相遇时ptr1跑了m圈,ptr2跑了n圈。因为ptr2速度是ptr1两倍,有:
2(x+k+mr) = x+k+nr
x+k = (n-m)r
因n和m均为整数且n>m,x+k应为整数圈。因为ptr1和ptr2在圈内位置为k,再跑x会到达圈起始点。从head跑x,同样会到达圈的起始点。所以讲ptr1移动到head,和ptr2以步长为1一起移动,相遇处就是圈的起始点。
0 0
- 第10题 Linked List Cycle II
- [LeetCode 第11题] -- Linked List Cycle II
- [LeetCode 第10题] -- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- cookie的技术实现
- Remove Duplicates from Sorted Array
- setContentView和inflate区别
- Berkeley套接字
- 用viso画C++类图
- 第10题 Linked List Cycle II
- ios swift学习日记2-基础部分
- Codeforces 474E Pillars dp+线段树(水
- php获取远程图片体积大小的实例
- Android---UI篇---DatePicker,TimePicker(日期和时间)
- Cookie的特点
- html表单(文本框、密码、单选、复选、提交、重置、普通、隐藏、文件按钮、下拉选项)
- ssh(Struts+spring+Hibernate)三大框架整合-简述
- 非常好的理解遗传算法的例子