Skip to content

Commit de8b9bc

Browse files
authored
Create redundant-connection.cpp
1 parent d012705 commit de8b9bc

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

C++/redundant-connection.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Time: O(nlog*n) ~= O(n), n is the length of the positions
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
7+
UnionFind union_find(2000);
8+
for (const auto& edge : edges) {
9+
if (!union_find.union_set(edge[0], edge[1])) {
10+
return edge;
11+
}
12+
}
13+
return {};
14+
}
15+
16+
private:
17+
class UnionFind {
18+
public:
19+
UnionFind(const int n) : set_(n), count_(n) {
20+
iota(set_.begin(), set_.end(), 0);
21+
}
22+
23+
int find_set(const int x) {
24+
if (set_[x] != x) {
25+
set_[x] = find_set(set_[x]); // Path compression.
26+
}
27+
return set_[x];
28+
}
29+
30+
bool union_set(const int x, const int y) {
31+
int x_root = find_set(x), y_root = find_set(y);
32+
if (x_root == y_root) {
33+
return false;
34+
}
35+
set_[min(x_root, y_root)] = max(x_root, y_root);
36+
--count_;
37+
return true;
38+
}
39+
40+
int length() const {
41+
return count_;
42+
}
43+
44+
private:
45+
vector<int> set_;
46+
int count_;
47+
};
48+
};

0 commit comments

Comments
 (0)