forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedundant Connection II.java
76 lines (66 loc) · 1.79 KB
/
Redundant Connection II.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Runtime: 3 ms (Top 24.18%) | Memory: 44.9 MB (Top 16.79%)
class Solution {
int[] dsu;
public int[] findRedundantDirectedConnection(int[][] edges) {
int n=edges.length;
int[] parent=new int[n+1];
Arrays.fill(parent,-1);
int[] e2=null;
int[] e1=null;
boolean twopt=false;
for(int[] edge: edges){
int from=edge[0];
int to=edge[1];
if(parent[to]==-1){
parent[to]=from;
}else{
twopt=true;
e2=edge;
e1=new int[]{parent[to],to};
break;
}
}
dsu=new int[edges.length+1];
for(int i=0;i<=edges.length;i++){
dsu[i]=i;
}
if(twopt==false){
int[] res=null;
for(int[] edge: edges){
int from=edge[0];
int to=edge[1];
int fromlead=find(from);
if(fromlead==to){
res=edge;
break;
}else{
dsu[to]=fromlead;
}
}
return res;
}else{
boolean iscycle=false;
for(int[] edge: edges){
if(edge==e2) continue;
int from =edge[0];
int to=edge[1];
int fromlead=find(from);
if(fromlead==to){
iscycle=true;
break;
}else{
dsu[to]=fromlead;
}
}
if(iscycle==true){
return e1;
}else{
return e2;
}
}
}
public int find(int x){
if(dsu[x]==x) return x;
return dsu[x]=find(dsu[x]);
}
}