当前位置:网站首页>0DFS中等 LeetCode6134. 找到离给定两个节点最近的节点
0DFS中等 LeetCode6134. 找到离给定两个节点最近的节点
2022-08-01 21:16:00 【18阿鲁】
描述
给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,每个节点 至多 有一条出边。
有向图用大小为 n 下标从 0 开始的数组 edges 表示,表示节点 i 有一条有向边指向 edges[i] 。如果节点 i 没有出边,那么 edges[i] == -1 。
同时给你两个节点 node1 和 node2 。
请你返回一个从 node1 和 node2 都能到达节点的编号,使节点 node1 和节点 node2 到这个节点的距离 较大值最小化。如果有多个答案,请返回 最小 的节点编号。如果答案不存在,返回 -1 。
注意 edges 可能包含环。
提示:
n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
0 <= node1, node2 < n
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-closest-node-to-given-two-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
可达性分析
Node1 和node2分别遍历一次,记录到每个结点的距离,然后遍历每个结点,在node1和node2都能到达的结点中选择node1和node2到达该结点较大值的最小的结点。
注意距离从1开始这样node1,node2的距离不会是0,方便排除掉哪些两个结点不能达到的结点。
class Solution {
public int closestMeetingNode(int[] edges, int node1, int node2) {
int n = edges.length;
int[] len = new int[n];
int[] len2 = new int[n];
int i = node1, j = node2;
int l1 = 1;
int l2 = 1;
while (i != -1 && len[i] == 0) {
len[i] = l1;
l1++;
i = edges[i];
}
int ans = -1;
int max = n+2;
while (j != -1 && len2[j] == 0) {
len2[j] = l2;
l2++;
j = edges[j];
}
for (int k = 0; k < n; k++) {
if (len[k] != 0 && len2[k] != 0) {
int tmp = Math.max(len[k],len2[k]);
if (max > tmp) {
max = tmp;
ans = k;
}
}
}
return ans;
}
}
边栏推荐
- 正则表达式
- Nacos 配置中心
- C Pitfalls and Defects Chapter 7 Portability Defects 7.9 Case Conversion
- C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
- 附录A printf、varargs与stdarg A.3 stdarg.h ANSI版的varargs.h
- Interview Blitz 70: What are sticky packs and half packs?How to deal with it?
- R语言 线性回归的有关方法
- 移植MQTT源码到STM32F407开发板上
- C专家编程 第1章 C:穿越时空的迷雾 1.1 C语言的史前阶段
- 【Jmeter常用断言组件】
猜你喜欢
Hiking, cured my mental internal friction
【接口测试】JMeter调用JS文件实现RSA加密
An online JVM FullGC made it impossible to sleep all night and completely crashed~
Day016 类和对象
wps excel 插入公式 整列
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.4 K&R C
响应式织梦模板清洁服务类网站
30+的女性测试人面试经验分享
51.【结构体初始化的两种方法】
ORI-GB-NP半乳糖介导冬凌草甲素/姜黄素牛血清白蛋白纳米粒的研究制备方法
随机推荐
[译] 容器和 Kubernetes 中的退出码完整指南
kubernetes各名词缩写
LeetCode·每日一题·1374.生成每种字符都是奇数个的字符串·模拟
记录第一次给开源项目提 PR
C专家编程 第1章 C:穿越时空的迷雾 1.5 今日之ANSI C
函数(二)
Review Set/Map basics with these two hooks
Kubernetes 如何实现组件高可用
Popular explanation: what is a clinical prediction model
An online JVM FullGC made it impossible to sleep all night and completely crashed~
【中文树库标记---CTB】
网红驼背矫正产品真的管用吗?如何预防驼背?医生说要这样做
Questions I don't know in database kernel interview(1)
如何优雅的性能调优,分享一线大佬性能调优的心路历程
C pitfalls and pitfalls Chapter 8 Suggestions and answers 8.2 Answers
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.5 ANSI C Today
R语言 线性回归的有关方法
C专家编程 序
MySQL 中出现的字符编码错误 Incorrect string value: ‘\x\x\x\x‘ for column ‘x‘
牛血清白蛋白-葡聚糖-叶黄素纳米颗粒/半乳糖白蛋白磁性阿霉素纳米粒的制备