Skip to content

Commit 9580e68

Browse files
committed
Runtime: 22 ms (Top 29.21%) | Memory: 9.9 MB (Top 41.59%)
1 parent 3109437 commit 9580e68

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1+
// Runtime: 22 ms (Top 29.21%) | Memory: 9.9 MB (Top 41.59%)
12
class Solution {
23
public:
34
/*
45
There are two cases for the tree structure to be invalid.
56
1) A node having two parents;
67
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.
910
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+
1213
int find(vector<int>& par, int n){
1314
if(par[n]==n || par[n]<0) return n;
1415
par[n] = find(par, par[n]);
1516
return par[n];
16-
}
17-
17+
}
18+
1819
void findSpecialEdge(vector<vector<int>>& edges, vector<int>& edgeA, vector<int>& edgeB){
1920
int len = edges.size();
2021
vector<int>par(len+1, 0);
@@ -23,26 +24,26 @@ class Solution {
2324
if(par[c]){
2425
edgeA = {par[c], c};
2526
edgeB = e;
26-
return;
27+
return;
2728
}else{
2829
par[c] = p;
2930
}
3031
}
3132
}
32-
33+
3334
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
3435
int len = edges.size();
3536
vector<int>parent(len+1, 0);
3637
for(int i=0; i<=len; i++) parent[i]=i;
37-
38+
3839
vector<int>edgeA={}; // 1st candidate
3940
vector<int>edgeB={}; // 2nd candidate
4041
findSpecialEdge(edges, edgeA, edgeB);
41-
42+
4243
for(vector<int> e : edges){
4344
int n1 = e[0];
4445
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
4647
continue;
4748
}
4849
int p1 = find(parent, n1);
@@ -56,7 +57,7 @@ class Solution {
5657
} else{
5758
parent[p2] = p1;
5859
}
59-
}
60+
}
6061
return edgeB;
6162
}
62-
};
63+
};

0 commit comments

Comments
 (0)