java: add «1636. Sort Array by Increasing Frequency»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0522d60931
commit
8caa3ec8bd
1 changed files with 35 additions and 0 deletions
35
java/sort-array-by-increasing-frequency.java
Normal file
35
java/sort-array-by-increasing-frequency.java
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
private HashMap<Integer, Integer> getFreqs(int[] nums) {
|
||||||
|
HashMap<Integer, Integer> freqs = new HashMap<>();
|
||||||
|
|
||||||
|
for (int x : nums) {
|
||||||
|
freqs.compute(x, (k, v) -> (v == null) ? 1 : v + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return freqs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] frequencySort(int[] nums) {
|
||||||
|
// get the frequencies
|
||||||
|
var freqs = getFreqs(nums);
|
||||||
|
|
||||||
|
// convert the array
|
||||||
|
Integer[] sortedNums = new Integer[nums.length];
|
||||||
|
for (int i = 0; i < nums.length; ++i) {
|
||||||
|
sortedNums[i] = nums[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
// sort it
|
||||||
|
Arrays.sort(
|
||||||
|
sortedNums, Comparator.comparing(k -> freqs.get((int) k)).thenComparing(k -> -(int) k));
|
||||||
|
|
||||||
|
// fill back the original array
|
||||||
|
for (int i = 0; i < nums.length; ++i) {
|
||||||
|
nums[i] = sortedNums[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
return nums;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue