141. Linked List Cycle
2016-07-26 16:43
253 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Copy 了一段外国人的清晰解释:
Since the runner’s speed is faster than walker,
4000
then it is guaranteed that runner will pass walker in some time. The only thing we need to prove is that the runner never jumps over walker so never meet. Suppose the runner jumps over walker in one unit of time, then we need to guarantee that 2 > distance + 1. So distance < 1 so distance = 0. This implies that runner already meets walker, contradiction. So runner will never jumps over walker.
Runner will pass walker + runner never jumps over = runner will meet walker.
时间复杂度不变,但是空间复杂度下降到了O(1)。算法如下:
Follow up:
Can you solve it without using extra space?
哈希表求解
简单处理就是将数据存放到哈希表,遍历的过程中判断是否存在,若存在说明有环。但是此算法在空间复杂度和时间复杂度上均为O(n),性能不佳。代码如下:public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> set = new HashSet<ListNode>(); ListNode temp = head; while(temp != null) { if(set.contains(temp)) return true; else set.add(temp); temp = temp.next; } return false; } }
赛跑算法
也就是Cycle Detection,具体可参考Floyd判圈算法。Copy 了一段外国人的清晰解释:
Since the runner’s speed is faster than walker,
4000
then it is guaranteed that runner will pass walker in some time. The only thing we need to prove is that the runner never jumps over walker so never meet. Suppose the runner jumps over walker in one unit of time, then we need to guarantee that 2 > distance + 1. So distance < 1 so distance = 0. This implies that runner already meets walker, contradiction. So runner will never jumps over walker.
Runner will pass walker + runner never jumps over = runner will meet walker.
时间复杂度不变,但是空间复杂度下降到了O(1)。算法如下:
public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) return false; ListNode slow = head; ListNode fast = head; //由于fast遍历速度较快 //所以只判断fast有没有下个节点和下下个节点 while(fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; if(slow == fast) { return true; } } return false; } }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法