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.
publicclassSolution {
publicint[]frequencySort(int[] nums) {
// Step 1: Count frequencies Map<Integer, Integer> map =new HashMap<>();
for (int num: nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
// Step 2: Convert array to list for easier sorting List<Integer> numList =new ArrayList<>();
for (int num: nums) {
numList.add(num);
}
// Step 3: Sort using custom comparator numList.sort((a, b) -> map.get(a) == map.get(b) ? b - a: map.get(a).compareTo(map.get(b)));
// Step 4: Convert list back to arrayfor (int i = 0; i < nums.length; i++) {
nums[i]= numList.get(i);
}
return nums;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicclassSolution {
publicint[]frequencySort(int[] nums) {
Map<Integer, Integer> map =new HashMap<>();
// count frequency of each number Arrays.stream(nums).forEach(n -> map.put(n, map.getOrDefault(n, 0) + 1));
// custom sortreturn Arrays.stream(nums).boxed()
.sorted((a,b) -> map.get(a) != map.get(b) ? map.get(a) - map.get(b) : b - a)
.mapToInt(n -> n)
.toArray();
}
}
1
2
3
4
5
6
7
8
9
10
11
from collections import Counter
deffrequency_sort(nums):
# Step 1: Count the frequency of each element freq = Counter(nums)
# Step 2: Sort based on frequency, and by value in decreasing order for ties in frequency nums.sort(key=lambda x: (freq[x], -x))
return nums