-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1636.Sort-Array-by-Increasing-Frequency.java
67 lines (50 loc) · 1.34 KB
/
1636.Sort-Array-by-Increasing-Frequency.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
63
64
65
66
67
// https://leetcode.com/problems/sort-array-by-increasing-frequency/
// algorithms
// Easy (63.81%)
// Total Accepted: 4,274
// Total Submissions: 6,698
// beats 100.0% of java submissions
class Solution {
public int[] frequencySort(int[] nums) {
Map<Integer, Item> map = new HashMap<>();
for (int n : nums) {
Item item = map.computeIfAbsent(n, Item::new);
item.inc();
}
List<Item> l = new ArrayList<>(map.values());
Collections.sort(l);
int[] res = new int[nums.length];
int idx = 0;
for (Item item : l) {
for (int i = 0; i < item.getNum(); i++) {
res[idx++] = item.getKey();
}
}
return res;
}
class Item implements Comparable<Item> {
private int key;
private int num;
public Item(int key) {
this.key = key;
}
private void inc() {
this.num++;
}
public int getKey() {
return key;
}
public int getNum() {
return num;
}
@Override
public int compareTo(Item o) {
if (num < o.getNum()) {
return -1;
} else if (num > o.getNum()) {
return 1;
}
return o.getKey() - key;
}
}
}