-
Notifications
You must be signed in to change notification settings - Fork 0
/
23rd July 2023.java
28 lines (26 loc) · 931 Bytes
/
23rd July 2023.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int[] frequencySort(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
List<Integer> keys = new ArrayList<>(frequencyMap.keySet());
//Logic was created by me , but code to keys.sort was given by GPT
keys.sort((a, b) -> {
int freqCompare = Integer.compare(frequencyMap.get(a), frequencyMap.get(b));
if (freqCompare == 0) {
return Integer.compare(b, a);
}
return freqCompare;
});
int[] result = new int[nums.length];
int index = 0;
for (int key : keys) {
int count = frequencyMap.get(key);
for (int i = 0; i < count; i++) {
result[index++] = key;
}
}
return result;
}
}