Linked List Cycle II
来源:互联网 发布:淘宝首页大图代码 编辑:程序博客网 时间:2024/06/06 11:45
题目:
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?
解答:前面判断是否有环就不说了,很容易,主要是要找到环的起始点,而且要求额外空间开销为常数,不然可以用个map就行。
先说说自己写的思路。相遇时,通过cur=cur->next循环直至回到本节点,可以得到环的节点个数N。然后从head开始,依次判断每个点走N步是否等于本身即可得到起始点。主要后面的复杂度相对较高。
说说在网上看到的思路。
当fast和slow相遇时,slow肯定没有遍历完链表,而fast已经在环内循环了n圈,如果slow走了s步,那么fast走了2s步,设环长为r,那么:
2s = s + nr => s = nr
设整个链表长为L,入口环与相遇点距离为x,起点到入口点的距离为a:
a + x = nr => a + x = (n - 1)r + r = (n - 1)r + L - a => a = (n - 1)r + (L - a - x)
其中,(L - a - x)是沿链表的方向,相遇点到环入口的距离,因此,从链表头到环入口点等于(n - 1)个内循环 + 相遇点到环入口的距离。
于是:从链表头和相遇点各设置一个指针,步长为1,两个指针必定相遇,且相遇第一点为环入口:
0 0
- 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
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 视频编码与封装方式详解
- BFM算法轮廓--基于文章 A Boundary-Fragment-Model for Object Detection
- ListView 实现带有Filpper效果的左右滑动删除 Item
- crmsql语句查询实体窗体实体字段关系信息
- JSP项目在MAC下的搭建——以本人 LPSS 项目为例
- Linked List Cycle II
- 面试算法(四十四)扑克牌的顺子
- [zoj 3774]Power of Fibonacci 数论(二次剩余 拓展欧几里得 等比数列求和)
- SAS程序实现日常报表的全自动化
- Java-JDK配置
- AJAXget方式传中文参数
- Android访问网络,使用HttpURLConnection还是HttpClient?
- struts2 s:if 多条件判断#的使用
- poj 3020 Antenna Placement(二分无向图 匈牙利)