File tree Expand file tree Collapse file tree 1 file changed +17
-10
lines changed Expand file tree Collapse file tree 1 file changed +17
-10
lines changed Original file line number Diff line number Diff line change 4
4
class Solution {
5
5
public:
6
6
vector<int > findRedundantDirectedConnection (vector<vector<int >>& edges) {
7
+ vector<int > cand1, cand2;
8
+ unordered_map<int , int > parent;
9
+ for (const auto & edge : edges) {
10
+ if (!parent.count (edge[1 ])) {
11
+ parent[edge[1 ]] = edge[0 ];
12
+ } else {
13
+ cand1 = {parent[edge[1 ]], edge[1 ]};
14
+ cand2 = edge;
15
+ }
16
+ }
7
17
UnionFind union_find (edges.size () + 1 );
8
18
for (const auto & edge : edges) {
19
+ if (edge == cand2) {
20
+ continue ;
21
+ }
9
22
if (!union_find.union_set (edge[0 ], edge[1 ])) {
10
- return edge;
23
+ return cand2. empty () ? edge : cand1 ;
11
24
}
12
25
}
13
- return {} ;
26
+ return cand2 ;
14
27
}
15
28
16
29
private:
17
30
class UnionFind {
18
31
public:
19
- UnionFind (const int n) : set_(n), count_(n) {
32
+ UnionFind (const int n) : set_(n) {
20
33
iota (set_.begin (), set_.end (), 0 );
21
34
}
22
35
@@ -32,17 +45,11 @@ class Solution {
32
45
if (x_root == y_root || y != y_root) {
33
46
return false ;
34
47
}
35
- set_[y_root] = x_root;
36
- --count_;
48
+ set_[y] = x_root;
37
49
return true ;
38
50
}
39
51
40
- int length () const {
41
- return count_;
42
- }
43
-
44
52
private:
45
53
vector<int > set_;
46
- int count_;
47
54
};
48
55
};
You can’t perform that action at this time.
0 commit comments