forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredundant-connection.java
59 lines (51 loc) · 1.19 KB
/
redundant-connection.java
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
57
58
59
/**
* Problem Name : Redundant Connection
* Concept Involved : Trees, Union Find
*
* Execution Time : 1 ms
* Memory Consumed : 39 mb
**/
class DUS{
public int[] parent;
public int n;
DUS(int n){
this.n = n;
parent = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
}
}
public int find(int u){
if(parent[u] != u){
parent[u] = find(parent[u]);
}
return parent[u];
}
public void union(int u, int v){
int pu = find(u);
int pv = find(v);
if(pu != pv){
parent[pv] = pu;
}
}
}
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] res = new int[2];
DUS dus = new DUS(edges.length+1);
for(int i=0; i<edges.length; i++){
int u = edges[i][0];
int v = edges[i][1];
int pu = dus.find(u);
int pv = dus.find(v);
if(pu != pv){
dus.union(u,v);
}
else{
res[0] = u;
res[1] = v;
}
}
return res;
}
}