当前位置:网站首页>【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)。
边栏推荐
- sys_kill系统调用
- Is TCP reliable?Why?
- qt-faststart installation and use
- A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
- 如何更好的理解的和做好工作?
- 如何用Redis实现分布式锁?
- 6133. Maximum number of packets
- @WebServlet注解(Servlet注解)
- 检查 Oracle 版本的 7 种方法
- npm npm
猜你喜欢

Secondary Vocational Network Security Competition B7 Competition Deployment Process

Classical Literature Reading--DLO

sys_kill system call

数据机构---第五章树与二叉树---二叉树的概念---应用题
![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)
[C language advanced] file operation (2)

What is CICD excuse me

solidity

2022 6th Strong Net Cup Part WP

工作5年,测试用例都设计不好?来看看大厂的用例设计总结

Building a cloud-native DevOps environment
随机推荐
cdh6打开oozieWeb页面,Oozie web console is disabled.
Flink Yarn Per Job - 提交流程一
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
怎样做才能让这条SQL变成一条危险的SQL?
Loading configuration of Nacos configuration center
Sql之各种Join
月薪12K,蝶变向新,勇往直前—她通过转行测试实现月薪翻倍~
[Camp Experience Post] 2022 Cybersecurity Summer Camp
使用Jenkins做持续集成,这个知识点必须要掌握
Flink学习第四天——完成第一个Flink 流批一体案例
洞见云原生微服务及微服务架构浅析
6133. 分组的最大数量
ELK log collection
cdh6 opens oozieWeb page, Oozie web console is disabled.
6132. 使数组中所有元素都等于零-快速排序法
Flink学习第五天——Flink可视化控制台依赖配置和界面介绍
numpy.unique
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
PostgreSQL Basics--Common Commands
A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing