mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
36 lines
810 B
Java
36 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;
|
||
|
}
|
||
|
}
|