【leetcode】No.141 Linked List Cycle
来源:互联网 发布:java定义常量 编辑:程序博客网 时间:2024/06/07 06:30
Total Accepted: 77477 Total Submissions: 211803 Difficulty: Medium
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断链表有无环的相关问题主要有四个:
1. 环的长度是多少?
2. 如何找到环中第一个节点(即Linked List Cycle II)?
3. 如何将有环的链表变成单链表(解除环)?
4. 如何判断两个单链表是否有交点?如何找到第一个相交的节点?
对第一个问题:
对于第一个问题,如果靠直觉来做的话,实现出来的时间复杂度为O(n2)。具体做法为:使用两个指针a, b。a从表头开始一步一步往前走,遇到nullptr则说明没有环,返回false;a每走一步,b重新从头开始走,如果遇到b==a.next,则说明有环true,如果遇到b==a,则说明暂时没有环,继续循环。
其实,有时间复杂度为O(n)的方法。即使用快慢指针来做。后来找到了复杂度O(n)的方法,使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到nullptr,则说明没有环,返回false;如果slow==fast,说明有环,返回true。(此时fast超了slow一圈)
有人肯定会有疑问,会问 为什么有环的情况下二者一定会相遇呢?这是因为,fast先进入环,之后slow进入。在圆环内,fast每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。
0 0
- Leetcode NO.141 Linked List Cycle
- 【leetcode】No.141 Linked List Cycle
- LeetCode--No.141--Linked List Cycle
- Leetcode NO.142 Linked List Cycle II
- LeetCode--No.142--Linked List Cycle II
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [leetcode 141] Linked List Cycle
- [leetcode]141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode[141]-Linked List Cycle
- leetcode-141-Linked List Cycle
- [Leetcode 141] Linked List Cycle
- leetcode 141: Linked List Cycle
- [Leetcode]#141 Linked List Cycle
- Active session量持续走高即将故障原因分析与优化建议
- tcl/tk参考——控制结构catch
- PHP: chr和pack、unpack那些事
- Swift字典
- nyoj-488-素数环
- 【leetcode】No.141 Linked List Cycle
- PHP: pack/unpack补遗
- 物联网 WIFI 一键配置原理(smartconfig) ESP8266/QCA4004
- js 设置cookie 读取cookie
- tcl/tk参考——控制结构error
- CXF发布restful WebService的入门例子(服务器端)
- App-UI测试的主要内容
- 关于css的标准盒子模型
- Android悬浮窗实现 使用WindowManager