Linked List Cycle 判断链表是否有环,如果有环,找到环的入口
来源:互联网 发布:阿里云解析设置 编辑:程序博客网 时间:2024/05/22 10:52
要求,空间复杂度为O(1)。
判断链表是否有环是一个经典的用双指针来解决的问题。
一个慢指针一次走一步,一个快指针一次走两步,
如果有环的话,它们最终会在环内相遇;如果没有环的话,最终快指针会先到达链表的尾部。
复杂度:
时间复杂度:O(n)
空间复杂度:O(1)
代码:
public boolean hasCycle(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return false; } ListNode slow = head.next, fast = head.next.next; while (fast != slow) { if (fast.next != null && fast.next.next != null) { // if no cycle, fast first will be null slow = slow.next; fast = fast.next.next; } else { return false; } } return true; }
下面的问题是如何判断环的入口。
假设x为环前面的路程(黑色路程),a为环入口到相遇点的路程(蓝色路程,假设顺时针走), c为环的长度(蓝色+橙色路程)
当快慢指针相遇的时候:
此时慢指针走的路程为Sslow = x + m * c + a
快指针走的路程为Sfast = x + n * c + a
2 Sslow = Sfast
2 * ( x + m*c + a ) = (x + n *c + a)
从而可以推导出:
x = (n - 2 * m )*c - a
= (n - 2 *m -1 )*c + c - a
即环前面的路程 = 数个环的长度(为可能为0) + c - a
什么是c - a?这是相遇点后,环后面部分的路程。(橙色路程)
所以,我们可以让一个指针从起点A开始走,让一个指针从相遇点B开始继续往后走,
2个指针速度一样,那么,当从原点的指针走到环入口点的时候(此时刚好走了x)
从相遇点开始走的那个指针也一定刚好到达环入口点。
所以2者会相遇,且恰好相遇在环的入口点。
最后,判断是否有环,且找环的算法复杂度为:
时间复杂度:O(n)
空间复杂度:O(1)
代码:
public ListNode detectCycle(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return null; } ListNode slow = head.next, fast = head.next.next; while (slow != fast) { if (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } else { return null; } } fast = head; while (fast != slow) { fast = fast.next; slow = slow.next; } return fast; }
1 0
- Linked List Cycle 判断链表是否有环,如果有环,找到环的入口
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- 判断链表是否有环 Linked List Cycle
- Linked List Cycle --判断链表是否有环
- leetcode--Linked List Cycle--判断链表是否有环
- Linked List Cycle 判断链表是否有环
- Linked List Cycle:判断链表是否有环
- 判断链表是否有环 Linked List Cycle, Linked List Cycle II
- 141. Linked List Cycle 判断单链表中是否有环
- leetcode_141. Linked List Cycle 判断链表中是否有环
- 141. Linked List Cycle (判断单链表中是否有环)
- 141. Linked List Cycle | 判断单链表是否有环
- Linked List Cycle 链表是否有环
- LeetCode | Linked List Cycle(判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle II(判断链表是否有环 - 二)
- 【leetcode】Linked List Cycle II,判断链表是否有环
- IE 11 访问Cordys BOP 4.3 问题分析
- php的编程效率
- Dialog自定义样式及使用笔记
- 尾部有圆圈的progressbar
- OSG中屏幕坐标和世界坐标的转化
- Linked List Cycle 判断链表是否有环,如果有环,找到环的入口
- 剑指offer26--数组中次数超过一半的数字
- QTableWidget常用(转载)
- silverlight treeview 节点顺序实例
- fedora freeze
- 有生之年, 游戏中再见 . (原因, 愿景)
- Android studio 快捷键使用
- js 定时器
- xtrabackup 增量,全量备数据库脚本