c++
class Solution {
public:
class UnionSet {
public:
int *father, n;
UnionSet(int n) : n(n) {
father = new int[n + 1];
for (int i = 0; i <= n; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] = (father[x] == x ? x : find(father[x]));
}
void merge(int a, int b) {
father[find(a)] = find(b);
return ;
}
};
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
UnionSet u(edges.size());
vector<int> ans;
for (auto edge : edges) {
if (u.find(edge[0]) != u.find(edge[1])) u.merge(edge[0], edge[1]);
else ans = edge;
}
return ans;
}
};
js
class UnionSet {
constructor(n) {
this.father = new Array(n);
for (var i = 0; i < n; i++) this.father[i] = i;
}
find(x) {
return this.father[x] = (this.father[x] == x ? x : this.find(this.father[x]));
}
merge(a, b) {
this.father[this.find(a)] = this.find(b);
}
};
var findRedundantConnection = function(edges) {
var u = new UnionSet(edges.length);
for (var edge of edges) {
if (u.find(edge[0]) == u.find(edge[1])) return edge;
u.merge(edge[0], edge[1]);
}
return [];
};