-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.js
64 lines (61 loc) · 1.47 KB
/
Solution2.js
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
class UnionFind {
constructor(n) {
this.p = Array.from({ length: n }, (_, i) => i);
this.size = Array(n).fill(1);
}
find(x) {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a, b) {
const pa = this.find(a);
const pb = this.find(b);
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
}
/**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantDirectedConnection = function (edges) {
const n = edges.length;
const ind = Array(n).fill(0);
for (const [_, v] of edges) {
++ind[v - 1];
}
const dup = [];
for (let i = 0; i < n; ++i) {
if (ind[edges[i][1] - 1] === 2) {
dup.push(i);
}
}
const uf = new UnionFind(n);
if (dup.length) {
for (let i = 0; i < n; ++i) {
if (i === dup[1]) {
continue;
}
if (!uf.union(edges[i][0] - 1, edges[i][1] - 1)) {
return edges[dup[0]];
}
}
return edges[dup[1]];
}
for (let i = 0; ; ++i) {
if (!uf.union(edges[i][0] - 1, edges[i][1] - 1)) {
return edges[i];
}
}
};