-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0684-redundant-connection.cpp
64 lines (55 loc) · 1.62 KB
/
0684-redundant-connection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Given undirected graph, return an edge that can be removed to make a tree
Ex. edges = [[1,2],[1,3],[2,3]] -> [2,3]
If n nodes & n edges, guaranteed a cycle
How to know creating cycle? When connecting a node already connected
Union Find: can find this redundant edge, track parents & ranks
Time: O(n)
Space: O(n)
*/
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
vector<int> parents;
vector<int> ranks;
for (int i = 0; i < n + 1; i++) {
parents.push_back(i);
ranks.push_back(1);
}
vector<int> result;
for (int i = 0; i < n; i++) {
int n1 = edges[i][0];
int n2 = edges[i][1];
if (!doUnion(parents, ranks, n1, n2)) {
result = {n1, n2};
break;
}
}
return result;
}
private:
int doFind(vector<int>& parents, int n) {
int p = parents[n];
while (p != parents[p]) {
parents[p] = parents[parents[p]];
p = parents[p];
}
return p;
}
bool doUnion(vector<int>& parents, vector<int>& ranks, int n1, int n2) {
int p1 = doFind(parents, n1);
int p2 = doFind(parents, n2);
if (p1 == p2) {
return false;
}
if (ranks[p1] > ranks[p2]) {
parents[p2] = p1;
ranks[p1] += ranks[p2];
} else {
parents[p1] = p2;
ranks[p2] += ranks[p1];
}
return true;
}
};