Skip to content

Commit 00e43ee

Browse files
authored
Update 3608-minimum-time-for-k-connected-components.js
1 parent 3f36528 commit 00e43ee

File tree

1 file changed

+25
-23
lines changed

1 file changed

+25
-23
lines changed

3608-minimum-time-for-k-connected-components.js

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,38 @@
44
* @param {number} k
55
* @return {number}
66
*/
7-
var minTime = function (n, edges, k) {
8-
let f = Array.from({ length: n }, (_, i) => i)
9-
7+
var minTime = function(n, edges, k) {
108
edges.sort((a, b) => b[2] - a[2])
11-
let count = n
12-
for (const [u, v, t] of edges) {
13-
if (union(u, v)) {
14-
count -= 1
15-
}
16-
if (count < k) {
17-
return t
18-
}
9+
const uf = new UF(n)
10+
let cnt = n
11+
12+
for(let i = 0; i < edges.length; i++) {
13+
const [u, v, t] = edges[i]
14+
if(uf.union(u, v)) cnt--
15+
if(cnt < k) return t
1916
}
2017
return 0
18+
};
2119

22-
function find(x) {
23-
if (x === f[x]) {
24-
return x
20+
class UF {
21+
constructor(n) {
22+
this.root = Array(n).fill(null).map((_, i) => i)
23+
}
24+
find(x) {
25+
if (this.root[x] !== x) {
26+
this.root[x] = this.find(this.root[x])
2527
}
26-
f[x] = find(f[x])
27-
return f[x]
28+
return this.root[x]
2829
}
29-
30-
function union(x, y) {
31-
x = find(x)
32-
y = find(y)
33-
if (x === y) {
30+
union(x, y) {
31+
const xr = this.find(x)
32+
const yr = this.find(y)
33+
if(xr === yr) {
3434
return false
35+
} else {
36+
this.root[yr] = xr
37+
return true
3538
}
36-
f[x] = y
37-
return true
39+
3840
}
3941
}

0 commit comments

Comments
 (0)