java: add «1636. Sort Array by Increasing Frequency»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-07-23 11:15:28 +02:00
parent 0522d60931
commit 8caa3ec8bd
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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;
}
}