Repository navigation
Expand file tree
/
Copy pathPotd
More file actions
56 lines (49 loc) · 1.4 KB
/
Copy pathPotd
File metadata and controls
56 lines (49 loc) · 1.4 KB
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
47
48
49
50
51
52
53
54
55
56
class Solution {
public int minSwaps(int[] nums) {
int n = nums.length;
int[] digitSum = new int[n];
for (int i = 0; i < n; i++) {
int x = nums[i],
sum = 0;
while (x > 0) {
sum += x % 10;
x /= 10;
}
digitSum[i] = sum;
}
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
Arrays.sort(indices, (a, b) -> {
if (digitSum[a] != digitSum[b]) {
return Integer.compare(digitSum[a], digitSum[b]);
}
return Integer.compare(nums[a], nums[b]);
});
int[] targetPos = new int[n];
for (int pos = 0; pos < n; pos++) {
targetPos[indices[pos]] = pos;
}
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
int components = n;
for (int i = 0; i < n; i++) {
int ri = find(parent, i);
int rj = find(parent, targetPos[i]);
if (ri != rj) {
parent[ri] = rj;
components--;
}
}
return n - components;
}
private int find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = find(parent, parent[x]);
}
return parent[x];
}
}