File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments