【链表】Linked List Cycle II
2016-01-25 11:08
323 查看
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
思路:
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
思路:
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var detectCycle = function(head) { if(head==null){ return null; } if(head.next==null){ return head; } var s=head,f=head.next.next; while(s!=f){ if(f==null||f.next==null){ return null; }else{ s=s.next; f=f.next.next; } } s=head; while(s!=f){ s=s.next; f=f.next; } return s; };
相关文章推荐
- python 常用模块
- 企业自托管代码管理gitlab的安装和相关配置
- Android studio Git功能使用教程
- xml格式解析
- Java数组的创建和使用
- String-常见工具收集
- java中文乱码解决之道(七)-----JSP页面编码过程
- java中文乱码解决之道(八)-----解决URL中文乱码问题
- ASP
- 青春最大的遗憾不是失败,而是后悔
- MyBatis 配置
- java中文乱码解决之道(六)-----javaWeb中的编码解码
- 【设计模式】抽象工厂模式
- spring的事物管理配置
- 谁曾是从谁的青春里走过,留下了笑靥
- 数组——字符串拆为数组及反相
- 欢迎使用CSDN-markdown编辑器
- 查看LINUX进程内存占用情况
- 关于SQLite索引对写入性能影响的测试
- Android框架