Class Solution
-
- All Implemented Interfaces:
public final class Solution2359 - Find Closest Node to Given Two Nodes\.
Medium
You are given a directed graph of
nnodes numbered from0ton - 1, where each node has at most one outgoing edge.The graph is represented with a given 0-indexed array
edgesof sizen, indicating that there is a directed edge from nodeito nodeedges[i]. If there is no outgoing edge fromi, thenedges[i] == -1.You are also given two integers
node1andnode2.Return the index of the node that can be reached from both
node1andnode2, such that the maximum between the distance fromnode1to that node, and fromnode2to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return-1.Note that
edgesmay contain cycles.Example 1:
Input: edges = 2,2,3,-1, node1 = 0, node2 = 1
Output: 2
Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.
Example 2:
Input: edges = 1,2,-1, node1 = 0, node2 = 2
Output: 2
Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.
Constraints:
n == edges.length<code>2 <= n <= 10<sup>5</sup></code>
-1 <= edges[i] < nedges[i] != i0 <= node1, node2 < n
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntegerclosestMeetingNode(IntArray edges, Integer node1, Integer node2)-
-
Method Detail
-
closestMeetingNode
final Integer closestMeetingNode(IntArray edges, Integer node1, Integer node2)
-
-
-
-