当前位置:网站首页>【Leetcode】2360. Longest Cycle in a Graph
【Leetcode】2360. Longest Cycle in a Graph
2022-08-01 23:47:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/longest-cycle-in-a-graph/
给定一个 n n n个点的有向图,每个点最多只有一条出边。给定每个点的出边指向的点,如果不存在则以 − 1 -1 −1标记。求长度最大的环的长度。若不存在环,则返回 − 1 -1 −1。
当然可以直接用Tarjan求一下最大的强联通分量。由于每个点只有一条出边,所以每个点只会存在于一个环中,从而可以直接模拟,直接从每个点出发,并且做标记,同时用一个哈希表记录步数。代码如下:
class Solution {
public:
int longestCycle(vector<int>& e) {
int n = e.size();
vector<bool> vis(n);
int res = -1;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
unordered_map<int, int> mp;
int x = i, time_stamp = 0;
while (true) {
mp[x] = ++time_stamp;
vis[x] = true;
// 找到环了
if (mp.count(e[x])) {
res = max(res, mp[x] - mp[e[x]] + 1);
break;
}
// 走到了死胡同
if (e[x] == -1 || vis[e[x]]) break;
// 向后走一步
x = e[x];
}
}
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。
边栏推荐
猜你喜欢
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
Data Organization --- Chapter 5 Trees and Binary Trees --- The Concept of Binary Trees --- Application Questions
Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
CDH6的Hue打开出现‘ascii‘ codec can‘t encode characters
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
很多人喜欢用多御安全浏览器,竟是因为这些原因
工作5年,测试用例都设计不好?来看看大厂的用例设计总结
WEB安全基础 - - - XRAY使用
nodejs--process
中职网络安全竞赛B7比赛部署流程
随机推荐
Calculate the angle of a line defined by two points
带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?
async和await用法介绍
Flink Yarn Per Job - 提交流程一
经典文献阅读之--DLO
Various Joins of Sql
Share an interface test project (very worth practicing)
【MySQL系列】MySQL数据库基础
6134. Find the closest node to the given two nodes - force double hundred code
DRF generating serialization class code
使用Jenkins做持续集成,这个知识点必须要掌握
路径压缩、、
sys_kill system call
Chrome书签插件,让你实现高效整理
12306抢票,极限并发带来的思考?
ELK log collection
数据机构---第五章树与二叉树---二叉树的概念---应用题
numpy.unique
FAST-LIO2代码解析(二)
TexturePacker使用文档