1
+ // Runtime: 22 ms (Top 29.21%) | Memory: 9.9 MB (Top 41.59%)
1
2
class Solution {
2
3
public:
3
4
/*
4
5
There are two cases for the tree structure to be invalid.
5
6
1) A node having two parents;
6
7
2) A circle exists
7
-
8
- If there are both invalid conditions, which means there is a node which has 2 parents and there is also a circle even after we invalid edgeB.
8
+
9
+ If there are both invalid conditions, which means there is a node which has 2 parents and there is also a circle even after we invalid edgeB.
9
10
In this case, we have to return edgeA. only in this way can we avoid both double parents and circle for the tree.
10
- */
11
-
11
+ */
12
+
12
13
int find (vector<int >& par, int n){
13
14
if (par[n]==n || par[n]<0 ) return n;
14
15
par[n] = find (par, par[n]);
15
16
return par[n];
16
- }
17
-
17
+ }
18
+
18
19
void findSpecialEdge (vector<vector<int >>& edges, vector<int >& edgeA, vector<int >& edgeB){
19
20
int len = edges.size ();
20
21
vector<int >par (len+1 , 0 );
@@ -23,26 +24,26 @@ class Solution {
23
24
if (par[c]){
24
25
edgeA = {par[c], c};
25
26
edgeB = e;
26
- return ;
27
+ return ;
27
28
}else {
28
29
par[c] = p;
29
30
}
30
31
}
31
32
}
32
-
33
+
33
34
vector<int > findRedundantDirectedConnection (vector<vector<int >>& edges) {
34
35
int len = edges.size ();
35
36
vector<int >parent (len+1 , 0 );
36
37
for (int i=0 ; i<=len; i++) parent[i]=i;
37
-
38
+
38
39
vector<int >edgeA={}; // 1st candidate
39
40
vector<int >edgeB={}; // 2nd candidate
40
41
findSpecialEdge (edges, edgeA, edgeB);
41
-
42
+
42
43
for (vector<int > e : edges){
43
44
int n1 = e[0 ];
44
45
int n2 = e[1 ];
45
- if (edgeB.size ()>0 && (edgeB[0 ]==n1 && edgeB[1 ]==n2)){ // invalidate edgeB
46
+ if (edgeB.size ()>0 && (edgeB[0 ]==n1 && edgeB[1 ]==n2)){ // invalidate edgeB
46
47
continue ;
47
48
}
48
49
int p1 = find (parent, n1);
@@ -56,7 +57,7 @@ class Solution {
56
57
} else {
57
58
parent[p2] = p1;
58
59
}
59
- }
60
+ }
60
61
return edgeB;
61
62
}
62
- };
63
+ };
0 commit comments