-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSortArrayByIncreasingFrequency.java
32 lines (28 loc) · 1.06 KB
/
SortArrayByIncreasingFrequency.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
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SortArrayByIncreasingFrequency {
public int[] frequencySort(int[] array) {
Map<Integer, Integer> frequencies = getFrequencies(array);
return toArray(Arrays.stream(array).boxed().sorted((a, b) -> {
if (frequencies.get(a).equals(frequencies.get(b))) return b - a;
return frequencies.get(a) - frequencies.get(b);
}).collect(Collectors.toList()));
}
private Map<Integer, Integer> getFrequencies(int[] array) {
final Map<Integer, Integer> frequencies = new HashMap<>();
for (int element : array) {
frequencies.put(element, frequencies.getOrDefault(element, 0) + 1);
}
return frequencies;
}
private int[] toArray(List<Integer> list) {
final int[] array = new int[list.size()];
for (int index = 0 ; index < list.size() ; index++) {
array[index] = list.get(index);
}
return array;
}
}