当前位置:网站首页>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;
};
边栏推荐
- 直播弱网优化
- Programmers architecture practice way: software architecture basic concepts and thinking
- "Global Digital Economy Conference" landed in N World, Rongyun provides communication cloud service support
- 劝退背后。
- C#/VB.NET 从PDF中提取表格
- XDR平台架构与关键技术解析
- Activiti产生的背景和作用
- [Detailed explanation of binary search plus recursive writing method] with all the code
- 2022年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多
- Lease recovery system based on PHP7.2+MySQL5.7
猜你喜欢
随机推荐
【TypeScript】Why choose TypeScript?
干货!一种被称为Deformable Butterfly(DeBut)的高度结构化且稀疏的线性变换
使用.NET简单实现一个Redis的高性能克隆版(一)
opencv学习—VideoCapture 类基础知识「建议收藏」
嵌入式软件组件经典架构与存储器分类
"Global Digital Economy Conference" landed in N World, Rongyun provides communication cloud service support
MySQL数据库实战(1)
小身材有大作用——光模块寿命分析(二)
For invoice processing DocuWare, cast off the yoke of the paper and data input, automatic processing all the invoice received
LeetCode——622.设计循环队列
build --repot
代码分析Objective-C中的深拷贝与浅拷贝
dataset数据集有哪些_数据集类型
Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million
Machine Learning (Chapter 1) - Feature Engineering
直播弱网优化
How to retrieve IDC research reports?
LeetCode——1161. 最大层内元素和
2022年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多
【TypeScript】为什么要选择 TypeScript?









