1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/java/sort-array-by-increasing-frequency.java

36 lines
810 B
Java
Raw Normal View History

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