-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode347.java
More file actions
33 lines (28 loc) · 906 Bytes
/
Copy pathleetcode347.java
File metadata and controls
33 lines (28 loc) · 906 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
package leetcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class leetcode347 {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> ret = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer>[] bucket = new List[nums.length + 1];
for(int key : map.keySet()) {
int frequency = map.get(key);
if(bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
bucket[frequency].add(key);
}
for(int i = bucket.length - 1; i >= 0 && ret.size() < k; i--) {
if(bucket[i] != null) {
ret.addAll(bucket[i]);
}
}
return ret;
}
}