diff --git a/java/sort-array-by-increasing-frequency.java b/java/sort-array-by-increasing-frequency.java new file mode 100644 index 0000000..823efbb --- /dev/null +++ b/java/sort-array-by-increasing-frequency.java @@ -0,0 +1,35 @@ +import java.util.Comparator; + +class Solution { + private HashMap getFreqs(int[] nums) { + HashMap 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; + } +}