Skip to content

Commit 07beac6

Browse files
committed
Add the solution for LC #3551
1 parent 3c68196 commit 07beac6

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package org.sean.graph;
2+
3+
import java.util.Arrays;
4+
5+
/***
6+
* 3551. Minimum Swaps to Sort by Digit Sum
7+
*/
8+
public class MinSwapsCounter {
9+
public int minSwaps(int[] nums) {
10+
int len = nums.length;
11+
12+
// <val, sum, pos>
13+
int[][] elements = new int[len][3];
14+
for (int i = 0; i < len; i++) {
15+
elements[i][0] = nums[i];
16+
17+
int elem = nums[i];
18+
int sum = 0;
19+
while (elem > 0) {
20+
sum += elem % 10;
21+
elem /= 10;
22+
}
23+
elements[i][1] = sum;
24+
elements[i][2] = i;
25+
}
26+
27+
int[] actualIndexes = new int[len];
28+
Arrays.sort(elements, (o1, o2) -> {
29+
if (o1[1] == o2[1]) { // sort by the min value
30+
return Integer.compare(o1[0], o2[0]);
31+
} else {
32+
return Integer.compare(o1[1], o2[1]);
33+
}
34+
});
35+
for (int i = 0; i < len; i++) {
36+
actualIndexes[i] = elements[i][2];
37+
}
38+
39+
// System.out.println(Arrays.toString(actualIndexes));
40+
41+
// Simplify the problem as sorting the array actualIndexes by swapping 2 elements
42+
// n - numOfCircles
43+
boolean[] visited = new boolean[len];
44+
int res = len;
45+
for (int i = 0; i < len; i++) {
46+
if (visited[i]) continue;
47+
int j = i;
48+
while (!visited[j]) {
49+
visited[j] = true;
50+
j = actualIndexes[j];
51+
}
52+
res--;
53+
}
54+
return res;
55+
}
56+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.sean.graph;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
public class MinSwapsCounterTest {
9+
10+
private MinSwapsCounter counter;
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
counter = new MinSwapsCounter();
15+
}
16+
17+
@Test
18+
public void minSwaps() {
19+
int cnt = counter.minSwaps(new int[]{18, 43, 34, 16});
20+
assertEquals(2, cnt);
21+
}
22+
}

0 commit comments

Comments
 (0)