684. Redundant Connection
Leetcode
題目
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]前置知識 - Union-Find 算法
說明
解答
Last updated
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]Last updated
var findRedundantConnection = function (edges) {
const parent = Array.from({ length: edges.length + 1 })
.map((_, index) => index)
function find(index) {
while (index !== parent[index]) {
index = parent[index];
}
return index
}
function union(u, v) {
let rootU = find(u);
let rootV = find(v);
if (rootU === rootV) {
return true;
}
parent[rootU] = rootV;
}
for (let edge of edges) {
const [u, v] = edge;
const isUnion = union(u, v)
if (isUnion) return [u, v];
}
return []
};