这道题采用的解法是桶排序,画草图如下
代码如下
//基于桶排序求解「前 K 个高频元素」
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
int length = nums.length;
List<Integer>[] list = new List[length + 1];
for (int key : map.keySet()) {
int i = map.get(key);
if (list[i] == null) {
list[i] = new ArrayList();
}
list[i].add(key);
}
int[] res = new int[k];
int j = 0;
for (int i = length; i>=0 && j < k; i--) {
if (list[i] != null) {
for (int num : list[i]) {
res[j++] = num;
}
}
}
return res;
}
}