-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProductSort.java
62 lines (39 loc) · 1.53 KB
/
ProductSort.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
public class Solution {
// Twilio 2020 OA problem
public static void main(String[] args) throws Exception {
Integer[] items = {8, 5, 5, 5, 5, 1, 1, 1, 4, 4};
Integer[] desiredOutput = {8, 4, 4, 1, 1, 1, 5, 5, 5, 5};
Integer[] output = sort(items);
if (!Arrays.equals(output, desiredOutput)) throw new Exception("Wrong result!");
System.out.println("OK");
}
//Time: O(nlogn) average, O(n^2) in worst case
//Space: O(logn) average, O(n) in worst case
//n is number of elements
public static Integer[] sort(Integer[] numbers) {
Integer[] sol = Arrays.copyOf(numbers, numbers.length);
Map<Integer, Integer> frequencies = new HashMap<>();
for(Integer num: numbers) {
frequencies.put(num, frequencies.getOrDefault(num, 0) + 1);
}
ProductComparator comparator = new ProductComparator(frequencies);
Arrays.sort(sol, comparator);
return sol;
}
private static class ProductComparator implements Comparator<Integer> {
Map<Integer, Integer> frequencies;
public ProductComparator(Map<Integer, Integer> frequencies) {
this.frequencies = frequencies;
}
@Override
public int compare(Integer o1, Integer o2) {
int freqComp = Integer.compare(
frequencies.get(o1),
frequencies.get(o2)
);
if (freqComp != 0) return freqComp;
return Integer.compare(o1, o2);
}
}
}