Open underwindfall opened 3 years ago
// https://www.bilibili.com/video/BV1mt411J79j
// path compression
// time O(nlog*n) == O(1)
class UnionFind {
class UnionFindSet {
private int[] parents;
private int[] ranks;
UnionFindSet(int n) {
parents = new int[n + 1];
ranks = new int[n + 1];
for (int i = 0; i < parents.length; i++) {
parents[i] = i;
ranks[i] = 1;
}
}
boolean Union(int u, int v) {
int pu = find(u);
int pv = find(v);
if (pu == pv)
return false;
if (ranks[pv] > ranks[pu]) {
parents[pu] = pv;
} else if (ranks[pu] > ranks[pv]) {
parents[pv] = pu;
} else {
parents[pv] = pu;
ranks[pu] += 1;
}
return true;
}
int find(int u) {
while (parents[u] != u) {
parents[u] = parents[parents[u]];
u = parents[u];
}
return u;
}
}
public int[] findRedundantConnection(int[][] edges) {
UnionFindSet s = new UnionFindSet(edges.length);
for (int[] edge : edges)
if (!s.Union(edge[0], edge[1]))
return edge;
return null;
}
}
https://leetcode-cn.com/problems/redundant-connection/
思路
[ ] 刷15mins
[ ] 刷5mins