当前位置:网站首页>LeetCode-142. 环形链表 II
LeetCode-142. 环形链表 II
2022-08-03 11:29:00 【边界流浪者】
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
提示:
链表中节点的数目范围在范围 [0, 104] 内
-105 <= Node.val <= 105
pos 的值为 -1 或者链表中的一个有效索引
进阶:你是否可以使用 O(1) 空间解决此题?
#include <iostream>
#include <unordered_map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
int index = 0;
ListNode *t = head;
if(t == nullptr){
return t;
}
hash[t] = index;
while(t->next!=nullptr){
t = t->next;
if(hash.count(t)!=0){
return t;
}else{
hash[t] = ++index;
}
}
return nullptr;
}
private:
unordered_map<ListNode *, int> hash;
};
边栏推荐
- 本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现
- 下午见!2022京东云数据库新品发布会
- FR9811S6 SOT-23-6 23V,2A同步降压DC/DC转换器
- html网页如何获取后台数据库的数据(html + ajax + php + mysql)
- [Wrong title] Circuit maintenance
- dataset数据集有哪些_数据集类型
- Simple implementation of a high-performance clone of Redis using .NET (1)
- 数据库一席谈:打造开源的数据生态,支撑产业数字化浪潮
- Fastjson反序列化
- 一个扛住 100 亿次请求的红包系统,写得太好了!!
猜你喜欢

技术总监需要会些什么?也太难了!
![[LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly](/img/19/a3f58d5a1150d99571205a7e2f7345.png)
[LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly

Dva.js 新手入门指南

html+css+php+mysql实现注册+登录+修改密码(附完整代码)
【一起学Rust】Rust包管理工具Cargo初步了解

【Star项目】小帽飞机大战(九)

本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现

云原生 Dev0ps 实践

MySQL database combat (1)

微信小程序获取用户手机号码
随机推荐
Binary search tree (search binary tree) simulation implementation (there is a recursive version)
opencv学习—VideoCapture 类基础知识「建议收藏」
深度学习:文本CNN-textcnn
dataset数据集有哪些_数据集类型
XDR平台架构与关键技术解析
Summary of redis basics - data types (strings, lists, sets, hashes, sets)
What is a smart contract?
[错题]电路维修
87.(cesium之家)cesium热力图(贴地形)
Redis发布订阅和数据类型
【文件IO的简单实现】
缓存--伪共享问题
Generate interface documentation online
机器比人更需要通证
What is the relationship between The Matrix and 6G?
【输出一个整数的的每一位,由高到低输出。使用递归和不使用递归】
Question G: Word Analysis ← Questions for the second provincial competition of the 11th Blue Bridge Cup Competition
本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现
优维低代码:Provider 构件
CADEditorX ActiveX 14.1.X