当前位置:网站首页>leetcode-6135:图中的最长环
leetcode-6135:图中的最长环
2022-08-01 07:50:00 【菊头蝙蝠】
leetcode-6135:图中的最长环
题目
题目连接
给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,其中每个节点 至多 有一条出边。
图用一个大小为 n 下标从 0 开始的数组 edges 表示,节点 i 到节点 edges[i] 之间有一条有向边。如果节点 i 没有出边,那么 edges[i] == -1 。
请你返回图中的 最长 环,如果没有任何环,请返回 -1 。
一个环指的是起点和终点是 同一个 节点的路径。
示例 1:

输入:edges = [3,3,4,2,3]
输出去:3
解释:图中的最长环是:2 -> 4 -> 3 -> 2 。
这个环的长度为 3 ,所以返回 3 。
示例 2:

输入:edges = [2,-1,3,1]
输出:-1
解释:图中没有任何环。
解题
方法一:内向基环树找环+时间戳
class Solution {
public:
int longestCycle(vector<int>& edges) {
int n=edges.size();
vector<int> time(n,0);
int res=-1;
for(int i=0,clock=1;i<n;i++){
if(time[i]) continue;
for(int x=i,start_time=clock;x>=0;x=edges[x]){
if(time[x]){
if(time[x]>=start_time){
res=max(res,clock-time[x]);
}
break;
}
time[x]=clock++;
}
}
return res;
}
};
边栏推荐
猜你喜欢

企业数据虚拟化综合指南

小程序更多的手势事件(左右滑动、放大缩小、双击、长按)

Image lossless compression software which works: try completely free JPG - C image batch finishing compression reduces weight tools | latest JPG batch dressing tools download

USB 协议 (二) 术语

案例实践 --- Resnet经典卷积神经网络(Mindspore)

Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?

最小生成树

22牛客多校1 C.Grab the Seat (几何 + 暴力)

如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法

The use of Golang: go template engine
随机推荐
日志导致线程Block的这些坑,你不得不防
数据分析6
走进音视频的世界——mp3封装格式
第02章 MySQL的数据目录【1.MySQL架构篇】【MySQL高级】
The socket option
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
Chapters 6 and 7 of Huawei Deep Learning Course
C语言学习概览(二)
Go supports OOP: use struct instead of class
13 - JUC CountDownLatch concurrent programming
Summary of test points about app updates in different ways
Gethostbyname \ getaddrinfo DNS domain name IP address is not safe
gethostbyname \ getaddrinfo 解析域名IP地址不安全的原因
VSCode插件推荐(Rust环境)
我的创作纪念日
USB 协议 (二) 术语
C语言学习概览(一)
Delphi MDI appliction 文档最大化显示、去掉最大化最小化等按钮
拳头游戏免版权音乐下载,英雄联盟无版权音乐,可用于视频创作、直播
请问用flinksql写入数据到clickhouse需要引入什么依赖吗?
