class Solution {
public int[] findRedundantConnection(int[][] edges) {
int max = Integer.MIN_VALUE;
for(int[] edge : edges){
for(int num : edge){
max = Math.max(max,num);
}
}
int[] fathers = new int[max + 1];
for(int i = 0;i <= max;i++){
fathers[i] = i;
}
for(int i = 0;i < edges.length;i++){
if(!union(fathers,edges[i][0],edges[i][1])){
return edges[i];
}
}
return null;
}
private int findRoot(int[] fathers,int i){
if(fathers[i] != i){
fathers[i] = findRoot(fathers,fathers[i]);
}
return fathers[i];
}
private boolean union(int[] fathers,int i,int j){
int rooti = findRoot(fathers,i);
int rootj = findRoot(fathers,j);
if(rooti != rootj){
fathers[rooti] = fathers[rootj];
return true;
}
return false;
}
}