Skip to content

Commit d8db1eb

Browse files
solves sort array by incresing frequency
1 parent cc954d5 commit d8db1eb

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@
405405
| 1619 | [Mean of Array After Removing Some Elements](https://leetcode.com/problems/mean-of-array-after-removing-some-elements) | [![Java](assets/java.png)](src/MeanOfArrayAfterRemovingSomeElements.java) | |
406406
| 1624 | [Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters) | [![Java](assets/java.png)](src/LargestSubStringBetweenTwoEqualCharacters.java) | |
407407
| 1629 | [Slowest Key](https://leetcode.com/problems/slowest-key) | [![Java](assets/java.png)](src/SlowestKey.java) | |
408-
| 1636 | [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency) | | |
408+
| 1636 | [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency) | [![Java](assets/java.png)](src/SortArrayByIncreasingFrequency.java) | |
409409
| 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation) | | |
410410
| 1646 | [Get Maximum in Generated Array](https://leetcode.com/problems/get-maximum-in-generated-array) | | |
411411
| 1652 | [Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb) | | |
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.Arrays;
2+
import java.util.HashMap;
3+
import java.util.List;
4+
import java.util.Map;
5+
import java.util.stream.Collectors;
6+
7+
public class SortArrayByIncreasingFrequency {
8+
public int[] frequencySort(int[] array) {
9+
Map<Integer, Integer> frequencies = getFrequencies(array);
10+
11+
return toArray(Arrays.stream(array).boxed().sorted((a, b) -> {
12+
if (frequencies.get(a).equals(frequencies.get(b))) return b - a;
13+
return frequencies.get(a) - frequencies.get(b);
14+
}).collect(Collectors.toList()));
15+
}
16+
17+
private Map<Integer, Integer> getFrequencies(int[] array) {
18+
final Map<Integer, Integer> frequencies = new HashMap<>();
19+
for (int element : array) {
20+
frequencies.put(element, frequencies.getOrDefault(element, 0) + 1);
21+
}
22+
return frequencies;
23+
}
24+
25+
private int[] toArray(List<Integer> list) {
26+
final int[] array = new int[list.size()];
27+
for (int index = 0 ; index < list.size() ; index++) {
28+
array[index] = list.get(index);
29+
}
30+
return array;
31+
}
32+
}

0 commit comments

Comments
 (0)