1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { int[] parent; public int[] findRedundantConnection(int[][] edges) { int N = edges.length + 1; parent = new int[N]; int[] result = new int[]{}; for (int i = 0; i < edges.length; i++) {
for (int j = 0; j < N; j++) { parent[j] = j; }
for (int j = 0; j < edges.length; j++) { if (i == j) { continue; }
int[] edge = edges[j]; union(edge[0], edge[1], parent); }
int count = 0; for (int j = 1; j < N; j++) { if (parent[j] == j) { count++; } }
if (count == 1) { result = edges[i]; } }
return result; }
public int find(int i , int[] parent){ if (i != parent[i]) { parent[i] = find(parent[i], parent); } return parent[i]; }
public void union(int i, int j,int[] parent){ int x = find(i, parent); int y = find(j, parent); if (x != y) { parent[x] = y; } } }
|