From 8caa3ec8bde479a75b30cae7695e147c661edd74 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 23 Jul 2024 11:15:28 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1636.=20Sort=20Array=20by?= =?UTF-8?q?=20Increasing=20Frequency=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/sort-array-by-increasing-frequency.java | 35 ++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 java/sort-array-by-increasing-frequency.java 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; + } +}