Skip to content

Commit 5628481

Browse files
add a solution for 1636
1 parent 28170cf commit 5628481

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

Diff for: src/main/java/com/fishercoder/solutions/secondthousand/_1636.java

+27
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.fishercoder.solutions.secondthousand;
22

33
import java.util.ArrayList;
4+
import java.util.Arrays;
45
import java.util.Collections;
56
import java.util.HashMap;
67
import java.util.List;
@@ -39,4 +40,30 @@ public int[] frequencySort(int[] nums) {
3940
return result;
4041
}
4142
}
43+
44+
public static class Solution2 {
45+
46+
public int[] frequencySort(int[] nums) {
47+
Map<Integer, Integer> map = new HashMap<>();
48+
for (int num : nums) {
49+
map.put(num, map.getOrDefault(num, 0) + 1);
50+
}
51+
int[][] pairs = new int[map.size()][2];
52+
int i = 0;
53+
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
54+
pairs[i][0] = entry.getKey();
55+
pairs[i++][1] = entry.getValue();
56+
}
57+
Arrays.sort(pairs, (a, b) -> a[1] != b[1] ? a[1] - b[1] : b[0] - a[0]);
58+
int[] result = new int[nums.length];
59+
i = 0;
60+
for (int[] pair : pairs) {
61+
int count = pair[1];
62+
while (count-- > 0) {
63+
result[i++] = pair[0];
64+
}
65+
}
66+
return result;
67+
}
68+
}
4269
}

Diff for: src/test/java/com/fishercoder/secondthousand/_1636Test.java

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,26 @@
11
package com.fishercoder.secondthousand;
22

33
import com.fishercoder.solutions.secondthousand._1636;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static org.junit.Assert.assertArrayEquals;
7+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
88

99
public class _1636Test {
1010
private static _1636.Solution1 solution1;
11+
private static _1636.Solution2 solution2;
1112
private static int[] nums;
1213

13-
@BeforeClass
14-
public static void setup() {
14+
@BeforeEach
15+
public void setup() {
1516
solution1 = new _1636.Solution1();
17+
solution2 = new _1636.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
nums = new int[]{1, 1, 2, 2, 2, 3};
23+
assertArrayEquals(new int[]{3, 1, 1, 2, 2, 2}, solution2.frequencySort(nums));
2124
assertArrayEquals(new int[]{3, 1, 1, 2, 2, 2}, solution1.frequencySort(nums));
2225
}
2326

0 commit comments

Comments
 (0)