Leetcode 1636. Sort Array by Increasing Frequency
Given an array of integers nums
, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
Example 1:
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
Example 2:
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '1', '2', and '3' all have a frequency of 2, so they are sorted in decreasing order.
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100
Q: Are there any constraints on the time complexity we need to aim for? A: Not explicitly, but a time complexity better than O(n^2) would be suitable for a problem of this size.
Q: Are all elements in the given array integers within the given range? A: Yes.
Q: Can the input array contain any duplicates? A: Yes, the input array can have duplicates.
import java.util.*;
public class Solution {
public int[] frequencySort(int[] nums) {
// Step 1: Calculate Frequencies
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
// Step 2: Custom Sorting
Integer[] numsArray = Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(numsArray, (a, b) -> {
int freqCompare = freqMap.get(a).compareTo(freqMap.get(b));
if (freqCompare == 0) {
return b.compareTo(a); // If frequencies are the same, sort by value descending
}
return freqCompare; // Else, sort by frequency ascending
});
// Convert boxed Integer array back to int array
return Arrays.stream(numsArray).mapToInt(Integer::intValue).toArray();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(Arrays.toString(sol.frequencySort(new int[]{1, 1, 2, 2, 2, 3}))); // Output: [3, 1, 1, 2, 2, 2]
System.out.println(Arrays.toString(sol.frequencySort(new int[]{2, 3, 1, 3, 2}))); // Output: [1, 3, 3, 2, 2]
System.out.println(Arrays.toString(sol.frequencySort(new int[]{-1, 1, -6, 4, 5, -6, 1, 4, 1}))); // Output: [5, -1, 4, 4, -6, -6, 1, 1, 1]
}
}
n
is the number of elements in nums
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?