当前位置:网站首页>【LeetCode】141.环形链表
【LeetCode】141.环形链表
2022-07-31 10:03:00 【酥酥~】
题目
给你一个链表的头节点 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 <= 105
pos 为 -1 或者链表中的一个 有效索引 。
进阶:你能用 O(1)(即,常量)内存解决此问题吗?
题解
使用哈希表存储每一个结点
如果有环,就会有结点已存在
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> mynode;
while(head!=NULL)
{
if(mynode.count(head))
return true;
mynode.insert(head);
head=head->next;
}
return false;
}
};
快慢指针
如果存在环,则快指针会回到满指针后边然后追上慢指针
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != nullptr && fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};
边栏推荐
- 梅科尔工作室--鸿蒙十四天开发培训笔记(八)
- NowCoderTOP28-34二叉树——持续更新ing
- NowCoderTOP17-22 Binary search/sort - continuous update ing
- 出色的移动端用户验证
- 让动画每次重复前都有延迟
- Flink1.15 source code reading - PER_JOB vs APPLICATION execution process
- odoo14 | 附件上传功能及实际使用
- Rich text editor Tinymce
- 使用turtle画按钮
- Day113. Shangyitong: user authentication, Alibaba Cloud OSS, patient management
猜你喜欢

Meikle Studio--Hongmeng 14-day development training notes (8)

Canvas particles change various shapes js special effects

【软考软件评测师】2012综合知识历年真题
![[NLP] Interpretation of Transformer Theory](/img/5f/8e1b9e48310817a0443eb445479045.png)
[NLP] Interpretation of Transformer Theory

乐观锁和悲观锁

Redis Sentinel原理

loadrunner-controller-目标场景Schedule配置

二叉树的搜索与回溯问题(leetcode)

js实现2020年元旦倒计时公告牌

Come n times - 06. Print the linked list from end to end
随机推荐
js department budget and expenditure radar chart
零代码工具推荐 八爪鱼采集器
第二十二课,实例化(instancing)
Kotlin—基本语法(三)
Module eight
【TCP/IP】Network Model
Dart Log工具类
[NLP] Interpretation of Transformer Theory
Qt compile error: C2228: '.key' must have class/struct/union on the left
Kotlin—基本语法(二)
Use turtle to draw buttons
出色的移动端用户验证
Redis Sentinel原理
cocoaPods管理之后工程结构变化
Are postgresql range queries faster than index queries?
NowCoderTOP23-27二叉树遍历——持续更新ing
The fifth chapter
二叉树的搜索与回溯问题(leetcode)
开放麒麟 openKylin 自动化开发者平台正式发布
Come n times - 06. Print the linked list from end to end