当前位置:网站首页>【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)。
边栏推荐
猜你喜欢
【MySQL系列】MySQL索引事务
cdh的hue上oozie启动报错,Cannot allocate containers as requested resource is greater than maximum allowed
【MySQL系列】 MySQL表的增删改查(进阶)
在CentOS下安装MySQL
[C language advanced] file operation (2)
Enterprise firewall management, what firewall management tools are there?
Building a cloud-native DevOps environment
企业防护墙管理,有什么防火墙管理工具?
在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
ICLR 2022最佳论文:基于对比消歧的偏标签学习
随机推荐
What can be done to make this SQL into a dangerous SQL?
邻接表与邻接矩阵
程序员还差对象?new一个就行了
机器学习文本分类
LocalDateTime转为Date类型
[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环
WEB安全基础 - - - XRAY使用
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
IDEA common plugins
Avoid hidden text when loading fonts
Data Organization --- Chapter 5 Trees and Binary Trees --- The Concept of Binary Trees --- Application Questions
cdh6 opens oozieWeb page, Oozie web console is disabled.
企业防护墙管理,有什么防火墙管理工具?
Several interview questions about golang concurrency
Flink学习第四天——完成第一个Flink 流批一体案例
Classical Literature Reading--DLO
20220725 Information update
6134. 找到离给定两个节点最近的节点-力扣双百代码
【MySQL系列】 MySQL表的增删改查(进阶)
深度学习基础-基于Numpy的循环神经网络(RNN)实现和反向传播训练