forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
45 lines (43 loc) · 1.14 KB
/
Solution.java
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
class Solution {
private int[] p;
public boolean gcdSort(int[] nums) {
int n = 100010;
p = new int[n];
Map<Integer, List<Integer>> f = new HashMap<>();
for (int i = 0; i < n; ++i) {
p[i] = i;
}
int mx = 0;
for (int num : nums) {
mx = Math.max(mx, num);
}
for (int i = 2; i <= mx; ++i) {
if (f.containsKey(i)) {
continue;
}
for (int j = i; j <= mx; j += i) {
f.computeIfAbsent(j, k -> new ArrayList<>()).add(i);
}
}
for (int i : nums) {
for (int j : f.get(i)) {
p[find(i)] = find(j);
}
}
int[] s = new int[nums.length];
System.arraycopy(nums, 0, s, 0, nums.length);
Arrays.sort(s);
for (int i = 0; i < nums.length; ++i) {
if (s[i] != nums[i] && find(nums[i]) != find(s[i])) {
return false;
}
}
return true;
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}