1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/sort-array-by-increasing-frequency.java
2024-07-23 11:15:28 +02:00

35 lines
810 B
Java

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