-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathTopKFreq.java
More file actions
35 lines (30 loc) · 842 Bytes
/
TopKFreq.java
File metadata and controls
35 lines (30 loc) · 842 Bytes
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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int[] topKFrequent(int[] nums, int k){
Map<Integer, Integer> count = new HashMap<>();
for(int n : nums){
count.put(n, count.getOrDefault(n, 0) + 1);
}
List<Integer>[] freq = new List[nums.length + 1];
for(int i = 0; i < freq.length; i++){
freq[i] = new ArrayList<>;
}
for(Map.Entry<Integer, Integer> entry : count.entrySet()){
freq[entry.getValue()].add(entry.getKey());
}
int[] res = new int[k];
int index = 0;
for(int i = freq.length - 1; i > 0 && index < k; i--){
for(int n : freq[i]) {
res[index++] = n;
if(index == k){
return res;
}
}
}
return res;
}
}