-
Notifications
You must be signed in to change notification settings - Fork 0
/
347.Top_K_Frequent_Elements.java
57 lines (54 loc) · 1.8 KB
/
347.Top_K_Frequent_Elements.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
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.putIfAbsent(n, 0);
map.computeIfPresent(n, (a,b) -> b+1);
}
ArrayList<Integer>[] bucket = new ArrayList[nums.length+1];
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
if (bucket[e.getValue()] == null) {
bucket[e.getValue()] = new ArrayList<>();
}
bucket[e.getValue()].add(e.getKey());
}
int[] out = new int[k];
for (int i=nums.length; i>0; i--) {
if (bucket[i] != null) {
for (int j=0; j<bucket[i].size(); j++) {
out[--k] = bucket[i].get(j);
if (k==0) {
return out;
}
}
}
}
return out;
}
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.putIfAbsent(n, 0);
map.computeIfPresent(n, (a,b) -> b+1);
}
Map<Integer, List<Integer>> rev = new HashMap<>();
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
rev.putIfAbsent(e.getValue(), new ArrayList<>());
rev.get(e.getValue()).add(e.getKey());
}
int[] out = new int[k];
for (int i=nums.length; i>0; i--) {
if (rev.containsKey(i)) {
for (int j=0; j<rev.get(i).size(); j++) {
out[--k] = rev.get(i).get(j);
if (k==0) {
return out;
}
}
}
}
return out;
}
}