[LeetCode] Linked List Cycle II, Solution
2015-08-18 11:36
453 查看
Question :
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
Anaylsis :
首先,比较直观的是,先使用Linked List Cycle I的办法,判断是否有cycle。如果有,则从头遍历节点,对于每一个节点,查询是否在环里面,是个O(n^2)的法子。但是仔细想一想,发现这是个数学题。
如下图,假设linked list有环,环长Y,环以外的长度是X。
现在有两个指针,第一个指针,每走一次走一步,第二个指针每走一次走两步,如果他们走了t次之后相遇在K点
那么 指针一 走的路是 t = X + nY + K ①
指针二 走的路是 2t = X + mY+ K ② m,n为未知数
把等式一代入到等式二中, 有
2X + 2nY + 2K = X + mY + K
=> X+K = (m-2n)Y ③
这就清晰了,X和K的关系是基于Y互补的。等于说,两个指针相遇以后,再往下走X步就回到Cycle的起点了。这就可以有O(n)的实现了。
from : http://fisherlei.blogspot.tw/2013/11/leetcode-linked-list-cycle-ii-solution.html
Code :
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?
Anaylsis :
首先,比较直观的是,先使用Linked List Cycle I的办法,判断是否有cycle。如果有,则从头遍历节点,对于每一个节点,查询是否在环里面,是个O(n^2)的法子。但是仔细想一想,发现这是个数学题。
如下图,假设linked list有环,环长Y,环以外的长度是X。
现在有两个指针,第一个指针,每走一次走一步,第二个指针每走一次走两步,如果他们走了t次之后相遇在K点
那么 指针一 走的路是 t = X + nY + K ①
指针二 走的路是 2t = X + mY+ K ② m,n为未知数
把等式一代入到等式二中, 有
2X + 2nY + 2K = X + mY + K
=> X+K = (m-2n)Y ③
这就清晰了,X和K的关系是基于Y互补的。等于说,两个指针相遇以后,再往下走X步就回到Cycle的起点了。这就可以有O(n)的实现了。
from : http://fisherlei.blogspot.tw/2013/11/leetcode-linked-list-cycle-ii-solution.html
Code :
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { if(!head) return NULL; struct ListNode* slow=head; struct ListNode* fast=head; while(fast && fast->next) { fast = fast->next->next; slow = slow->next; if (slow == fast) break; } if(!fast || !fast->next) return NULL; while (slow != head) { slow = slow->next; head = head->next; } return slow; }
相关文章推荐
- GIS开发站点收藏
- Uri详解之——Uri结构与代码提取
- 社説 20150818 新国立競技場 「選手第一」の視点を忘れずに
- mt7620 openwrt编译,修改dts文件
- LeetCode Implement Queue using Stacks
- 常用字符串的截取
- 设计模式之创建者模式
- 四种不同的NAT类型
- 整合activiti过程中遇到的一些错误
- Maven 使用指南(1): 概述
- Maven 使用指南(2): 第一个例子Hello World
- LeetCode Implement Queue using Stacks
- tengine 黑白名单
- hdu 1166 敌兵布阵(线段树单点更新,区间查询)
- EGOTableViewPullRefresh实现下拉刷新
- 获取键盘鼠标不动的时间
- 日经社説 20150818 踊り場経済には景気対策でなく改革を
- Msql和SQL server时间类型
- WebService实例&调用本质&权限控制
- Java中抽象的总结