题目
题源
代码
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int num : nums) {
hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
}
List<Integer>[] buckets = new ArrayList[nums.length + 1];
for(int key : hashMap.keySet()) {
int val = hashMap.get(key);
if (buckets[val] == null) {
buckets[val] = new ArrayList<>();
}
buckets[val].add(key);
}
List<Integer> list = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0 && list.size() < k; i--) {
if (buckets[i] == null) continue;
if (buckets[i].size() <= (k - list.size())) {
list.addAll(buckets[i]);
} else {
list.addAll(buckets[i].subList(0, k - list.size()));
}
}
int[] res = new int[k];
for (int i = 0; i < k; i++) {
res[i] = list.get(i);
}
return res;
}
}