1998. GCD Sort of an Array

Description

image-20210915232017656

image-20210915232028365

Solution

Because we are using gcd to transfer numbers, so the number which shares the same factor should in the same set. So we could use Union-Find to mark numbers.

There is also a tricky point that how to get the prime factor of one number.

https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/

Code

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
46
const  int N = 1E5+1;
class Solution {
int p[N];
static bool cmp(int& a, int &b){return a < b;}
public:
void merge(int a, int b){
int x = find(a), y = find(b);
if(x != y){
p[x] = y;
}
}

int find(int a){
if(a != p[a]){
p[a] = find(p[a]);
}
return p[a];
}

bool gcdSort(vector<int>& nums) {
for(int i = 1; i < N; i++) p[i] = i;
vector<int> nums2 = nums;
for(int i = 0; i < nums.size(); i++){
int tmp = nums[i];
for(int j = 2; j <= tmp/j ; j++){
bool flag = false;
while(tmp % j == 0){
tmp /= j;
flag = true;
}
if(flag)
merge(nums[i], j);
}
if(tmp > 1)
merge(nums[i], tmp);
}
sort(nums.begin(), nums.end(),cmp);
for(int i = 0; i < nums.size(); i++){
if(nums[i] == nums2[i])
continue;
if(find(nums[i]) != find(nums2[i]))
return false;
}
return true;
}
};

image-20210915235655302