classSolution: defclosestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: n, min_dis, ans = len(edges), len(edges), -1 defcalc_dis(x: int) -> List[int]: dis = [n] * n d = 0 while x >= 0and dis[x] == n: dis[x] = d d += 1 x = edges[x] return dis for i, d inenumerate(map(max, zip(calc_dis(node1), calc_dis(node2)))): if d < min_dis: min_dis, ans = d, i return ans
classSolution { public: intclosestMeetingNode(vector<int> &edges, int node1, int node2){ int n = edges.size(), min_dis = n, ans = -1; auto calc_dis = [&](int x) -> vector<int> { vector<int> dis(n, n); for (int d = 0; x >= 0 && dis[x] == n; x = edges[x]) dis[x] = d++; return dis; }; auto d1 = calc_dis(node1), d2 = calc_dis(node2); for (int i = 0; i < n; ++i) { int d = max(d1[i], d2[i]); if (d < min_dis) { min_dis = d; ans = i; } } return ans; } };
funcclosestMeetingNode(edges []int, node1, node2 int)int { n := len(edges) calcDis := func(x int) []int { dis := make([]int, n) for i := range dis { dis[i] = n } for d := 0; x >= 0 && dis[x] == n; x = edges[x] { dis[x] = d d++ } return dis }
d1 := calcDis(node1) d2 := calcDis(node2) minDis, ans := n, -1 for i, d := range d1 { if d2[i] > d { d = d2[i] } if d < minDis { minDis, ans = d, i } } return ans }