Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit66cd20c

Browse files
authored
Create 2359-find-closest-node-to-given-two-nodes.kt
1 parent31aaa14 commit66cd20c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
classSolution {
2+
funclosestMeetingNode(edges:IntArray,node1:Int,node2:Int):Int {
3+
val adj=HashMap<Int,MutableList<Int>>().apply {
4+
for ((u, v)in edges.withIndex()) {
5+
this[u]= getOrDefault(u, mutableListOf<Int>()).apply { add(v) }
6+
}
7+
}
8+
9+
funbfs(node:Int,distMap:HashMap<Int,Int>) {
10+
with (LinkedList<Pair<Int,Int>>()) {
11+
addLast(node to0)
12+
distMap[node]=0
13+
while (isNotEmpty()) {
14+
val (node, dist)= removeFirst()
15+
adj[node]?.forEach { nei->
16+
if (nei!in distMap) {
17+
addLast(nei to dist+1)
18+
distMap[nei]= dist+1
19+
}
20+
}
21+
}
22+
}
23+
}
24+
25+
val node1Dist=HashMap<Int,Int>()
26+
val node2Dist=HashMap<Int,Int>()
27+
bfs(node1, node1Dist)
28+
bfs(node2, node2Dist)
29+
30+
var res=-1
31+
var resDist=Integer.MAX_VALUE
32+
for (iin edges.indices) {
33+
if (iin node1Dist&& iin node2Dist) {
34+
val dist= maxOf(node1Dist[i]!!, node2Dist[i]!!)
35+
if (dist< resDist) {
36+
res= i
37+
resDist= dist
38+
}
39+
}
40+
}
41+
42+
return res
43+
}
44+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp