当前位置:网站首页>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;
};
边栏推荐
猜你喜欢

面试官:SOA 和微服务的区别?这回终于搞清楚了!

XDR平台架构与关键技术解析

2022年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

嵌入式软件组件经典架构与存储器分类

MySQL database combat (1)

Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million

成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...

Redis发布订阅和数据类型

如何检索IDC研究报告?
【一起学Rust】Rust的Hello Rust详细解析
随机推荐
机器比人更需要通证
3分钟实现内网穿透(基于ngrok实现)
基于PHP7.2+MySQL5.7的回收租凭系统
【无标题】函数,对象,方法的区别
SmobilerService 推送实现
ABAB-740新语法
【LeetCode—第2题 两数之和 代码详解 】附有源码,可直接复制
How to use outside the PHP command in the container
Babbitt | Metaverse daily must-read: Players leave, platforms are shut down, and the digital collection market is gradually cooling down. Where is the future of the industry?...
实至名归!九章云极DataCanvas公司荣获智能制造领域多项殊荣
零拷贝、MMAP、堆外内存,傻傻搞不明白...
Analysis of the idea of the complete knapsack problem
Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems
一个扛住 100 亿次请求的红包系统,写得太好了!!
【HCIP持续更新】STP协议相关保护机制
XDR平台架构与关键技术解析
【输出一个整数的的每一位,由高到低输出。使用递归和不使用递归】
Classical Architecture and Memory Classification of Embedded Software Components
程序员架构修炼之道:如何设计出可持续演进的系统架构?
深度学习:文本CNN-textcnn