Skip to content

Commit 94620c3

Browse files
authored
Update redundant-connection-ii.cpp
1 parent 98d4417 commit 94620c3

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

C++/redundant-connection-ii.cpp

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,32 @@
44
class Solution {
55
public:
66
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+
}
717
UnionFind union_find(edges.size() + 1);
818
for (const auto& edge : edges) {
19+
if (edge == cand2) {
20+
continue;
21+
}
922
if (!union_find.union_set(edge[0], edge[1])) {
10-
return edge;
23+
return cand2.empty() ? edge : cand1;
1124
}
1225
}
13-
return {};
26+
return cand2;
1427
}
1528

1629
private:
1730
class UnionFind {
1831
public:
19-
UnionFind(const int n) : set_(n), count_(n) {
32+
UnionFind(const int n) : set_(n) {
2033
iota(set_.begin(), set_.end(), 0);
2134
}
2235

@@ -32,17 +45,11 @@ class Solution {
3245
if (x_root == y_root || y != y_root) {
3346
return false;
3447
}
35-
set_[y_root] = x_root;
36-
--count_;
48+
set_[y] = x_root;
3749
return true;
3850
}
3951

40-
int length() const {
41-
return count_;
42-
}
43-
4452
private:
4553
vector<int> set_;
46-
int count_;
4754
};
4855
};

0 commit comments

Comments
 (0)