-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSortArrayByIncreasingFrequency.java
More file actions
37 lines (31 loc) · 1.01 KB
/
SortArrayByIncreasingFrequency.java
File metadata and controls
37 lines (31 loc) · 1.01 KB
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
29
30
31
32
33
34
35
36
37
package array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/sort-array-by-increasing-frequency
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class SortArrayByIncreasingFrequency {
public int[] frequencySort(int[] nums) {
Map<Integer, Integer> freqMap = buildFreqMap(nums);
return Arrays.stream(nums)
.boxed()
.sorted((a, b) -> compare(a, b, freqMap))
.mapToInt(v -> v)
.toArray();
}
private Map<Integer, Integer> buildFreqMap(int[] nums) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.merge(num, 1, Integer::sum);
}
return freqMap;
}
private int compare(int a, int b, Map<Integer, Integer> freqMap) {
int result = Integer.compare(freqMap.get(a), freqMap.get(b));
return result != 0 ? result : Integer.compare(b, a);
}
}