当前位置:网站首页>LeetCode 0141. 环形链表 - 三种方法解决
LeetCode 0141. 环形链表 - 三种方法解决
2022-07-28 03:43:00 【Tisfy】
【LetMeFly】三种方法解决:141.环形链表
力扣题目链接:https://leetcode.cn/problems/linked-list-cycle/
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
示例 1:

输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:

输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:

输入:head = [1], pos = -1 输出:false 解释:链表中没有环。
提示:
- 链表中节点的数目范围是
[0, 104] -105 <= Node.val <= 105pos为-1或者链表中的一个 有效索引 。
进阶:你能用 O(1)(即,常量)内存解决此问题吗?
方法一:哈希表
原理很简单,遍历链表,用哈希表记录遍历过的节点。
遍历过程中,如果发现某个节点已经存在于哈希表中了,就说明这个节点遍历过了,也就是说有环
一旦遍历到了“next为空”的某个节点,就说明这个节点是链表的最后一个节点,也就是说无环
- 时间复杂度 O ( n ) O(n) O(n),其中 n n n是链表中节点的个数。C++中若使用
unordered_set,则插入和判断是否存在的复杂度都为 O ( 1 ) O(1) O(1) - 空间复杂度 O ( n ) O(n) O(n)
AC代码
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> se;
while (head) {
if (se.count(head))
return true;
se.insert(head);
head = head->next;
}
return false;
}
};
方法二:快慢指针
道理也不难,用两个指针,初始位置都指向链表头节点。
每次快指针向后移动两个节点,慢指针向后移动一个节点。
如果快指针移动到了链表尾部,就说明链表无环
如果快慢指针相遇了,就说明链表有环
**注意:**若有环,则快慢指针一定会相遇。因为快指针一定比慢指针提前进入到环中,等慢指针也进入环中后,快指针一定会追上满指针(因为速度是慢指针的两倍),并且一定不会不相遇而直接跳过去(慢指针移动前的旧位置和移动后的新位置共 2 2 2个节点,快指针一次前进 2 2 2个节点,必定踩上一个)
- 时间复杂度 O ( n ) O(n) O(n),其中 n n n是链表中节点的个数。慢指针的速度是快指针的一半,快指针会在两圈内追上慢指针
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head)
return false;
ListNode *fast = head, *slow = head;
do {
if (!fast->next || !fast->next->next) {
// 走到尾了
return false;
}
fast = fast->next->next;
slow = slow->next;
} while (fast != slow);
return fast == slow;
}
};
方法三:为了过题而过题
这个方法不实用,但是能够用简短的代码通过该题。
题目说了链表长度最多为 1 0 4 10^4 104,因此我们可以遍历链表的同时计数,如果节点个数超过了 1 0 4 10^4 104,就说明有节点遍历了不只一次,即说明链表中有环。
- 时间复杂度 O ( n ∨ C ) O(n \vee C) O(n∨C),其中 n n n是链表中节点的个数。 C C C是链表中节点的最大数目(本题为 1 0 4 10^4 104)
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
int count = 0;
while (head) {
count++;
if (count > 10000)
return true;
head = head->next;
}
return false;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126017056
边栏推荐
- Collection | 0 basic open source data visualization platform flyfish large screen development guide
- Redis source code analysis (who says C language can't analyze it?)
- "Xiaodeng" network equipment monitoring in operation and maintenance
- ES6 from entry to mastery 07: Deconstruction assignment
- 动态规划——509. 斐波那契数
- The latest version of pagoda installs the zip extension, and PHP -m does not display the processing method
- Swift中的协议
- ASEMI整流桥GBPC5010,GBPC5010参数,GBPC5010大小
- 单调栈——739. 每日温度
- Mouse operation and response
猜你喜欢

动态规划——509. 斐波那契数

How to uninstall clean ZABBIX service? (super detailed)

Prefix-Tuning: Optimizing Continuous Prompts for Generation

The latest version of pagoda installs the zip extension, and PHP -m does not display the processing method

高等数学(第七版)同济大学 习题3-4 个人解答(前8题)

Redis basic operation

In December, the PMP Exam adopted the new syllabus for the first time. How to learn?
![[leetcode] 34. Find the first and last positions of elements in the sorted array](/img/f0/3eaa33fa7b13abe5f27b136239507d.png)
[leetcode] 34. Find the first and last positions of elements in the sorted array

AI chief architect 12 AICA Baidu OCR vertical large-scale landing practice

TypeError: ufunc ‘bitwise_ and‘ not supported for the input types, and the inputs could not be safely
随机推荐
某宝模拟登录,减少二次验证的方法
C语言力扣第45题之跳跃游戏 II。遍历跳跃
A treasure simulates login and reduces the method of secondary verification
递归和非递归分别实现求第n个斐波那契数
Interface automation test, complete introduction
【论文笔记】基于深度学习的移动机器人自主导航实验平台
一篇文章掌握Postgresql中对于日期类数据的计算和处理
MangoPapa 的实用小脚本(目录篇)
一文读懂Plato Farm的ePLATO,以及其高溢价缘由
Xctf attack and defense world web master advanced area php2
动态规划——474. 一和零
95后阿里P7晒出工资单:真的是狠狠扎心了...
搬家通知!
Assembly method of golang Gorm query arbitrary fields
数据挖掘-02
The wonderful use of asemi rectifier bridge GBPC3510 in DC brush motor
VBA reads the create document of SQL in batches to create tables
【P4】 查看库文件两个历史版本的区别
Illustrated: detailed explanation of JVM memory layout
Do you regret doing automated testing?