当前位置:网站首页>Leetcode - 6135: the longest part of the figure
Leetcode - 6135: the longest part of the figure
2022-08-01 07:58:00 【chrysanthemum bat】
leetcode-6135:The longest part of the figure
题目
题目连接
给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,其中每个节点 至多 有一条出边.
图用一个大小为 n 下标从 0 开始的数组 edges 表示,节点 i 到节点 edges[i] 之间有一条有向边.如果节点 i 没有出边,那么 edges[i] == -1 .
请你返回图中的 最长 环,如果没有任何环,请返回 -1 .
一个环指的是起点和终点是 同一个 节点的路径.
示例 1:
输入:edges = [3,3,4,2,3]
输出去:3
解释:The longest part of the figure是:2 -> 4 -> 3 -> 2 .
这个环的长度为 3 ,所以返回 3 .
示例 2:
输入:edges = [2,-1,3,1]
输出:-1
解释:图中没有任何环.
解题
方法一:Within the base ring tree to find ring+时间戳
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;
}
};
边栏推荐
猜你喜欢
随机推荐
[Tear AHB-APB Bridge by hand]~ Why aren't the lower two bits of the AHB address bus used to represent the address?
VSCode插件推荐(Rust环境)
Go supports OOP: use struct instead of class
app 自动化 通过工具查看app 元素 (三)
Centos install php7.4, build hyperf, forward RDS
my creative day
pytest接口自动化测试框架 | 执行失败跳转pdb
Pod环境变量和initContainer
JVM: Runtime Data Area - PC Register (Program Counter)
我的创作纪念日
22牛客多校1 I. Chiitoitsu (概率dp)
22牛客多校1 J.Serval and Essay (启发式合并)
What do the values 1, 2, and 3 in nodetype mean?
leetcode-6134:找到离给定两个节点最近的节点
POJ2421道路建设题解
Pytest | skip module interface test automation framework
基于百度OCR的网站验证码在线识别
179. 最大数
app 自动化 打开app (二)
pytest接口自动化测试框架 | 跳过测试类