Skip to content

Commit 54def9d

Browse files
authored
Create 2709-greatest-common-divisor-traversal.kt
1 parent aa2a87c commit 54def9d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class UnionFind (val n: Int) {
2+
val parent = IntArray (n) { it }
3+
val size = IntArray (n) { 1 }
4+
var count = n
5+
6+
fun find(x: Int): Int {
7+
if (x != parent[x])
8+
parent[x] = find(parent[x])
9+
return parent[x]
10+
}
11+
12+
fun union(x: Int, y: Int) {
13+
val px = find(x)
14+
val py = find(y)
15+
if (px != py) {
16+
if (size[px] > size[py]) {
17+
parent[py] = px
18+
size[px] += size[py]
19+
} else {
20+
parent[px] = py
21+
size[py] += size[px]
22+
}
23+
count--
24+
}
25+
}
26+
}
27+
28+
class Solution {
29+
fun canTraverseAllPairs(nums: IntArray): Boolean {
30+
val uf = UnionFind (nums.size)
31+
val factorIndex = HashMap<Int, Int>()
32+
33+
for (i in nums.indices) {
34+
var n = nums[i]
35+
var f = 2
36+
37+
while (f * f <= n) {
38+
if (n % f == 0) {
39+
if (f in factorIndex)
40+
uf.union(i, factorIndex[f]!!)
41+
else
42+
factorIndex[f] = i
43+
while (n % f == 0)
44+
n /= f
45+
}
46+
f++
47+
}
48+
49+
if (n > 1) {
50+
if (n in factorIndex)
51+
uf.union(i, factorIndex[n]!!)
52+
else
53+
factorIndex[n] = i
54+
}
55+
}
56+
57+
return uf.count == 1
58+
}
59+
}

0 commit comments

Comments
 (0)