Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit54def9d

Browse files
authored
Create 2709-greatest-common-divisor-traversal.kt
1 parentaa2a87c commit54def9d

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+
classUnionFind (valn:Int) {
2+
val parent=IntArray (n) { it }
3+
val size=IntArray (n) {1 }
4+
var count= n
5+
6+
funfind(x:Int):Int {
7+
if (x!= parent[x])
8+
parent[x]= find(parent[x])
9+
return parent[x]
10+
}
11+
12+
fununion(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+
classSolution {
29+
funcanTraverseAllPairs(nums:IntArray):Boolean {
30+
val uf=UnionFind (nums.size)
31+
val factorIndex=HashMap<Int,Int>()
32+
33+
for (iin nums.indices) {
34+
var n= nums[i]
35+
var f=2
36+
37+
while (f* f<= n) {
38+
if (n% f==0) {
39+
if (fin 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 (nin 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)

[8]ページ先頭

©2009-2025 Movatter.jp