一、题目描述
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入:nums = [1,1,1,2,2,3], k = 2
输出:[1,2]
示例 2:
输入:nums = [1], k = 1
输出:[1]
示例 3:
输入:nums = [1,2,1,2,1,2,3,1,3,2], k = 2
输出:[1,2]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。
二、题目解析
1、堆
我们可以利用堆的思想:建立一个堆,然后遍历「出现次数数组」:
如果堆的元素个数小于 k,就可以直接插入堆中。
如果堆的元素个数等于 k,则检查堆顶与当前出现次数的大小。如果堆顶更大,说明至少有 k 个数字的出现次数比当前值大,故舍弃当前值;否则,就弹出堆顶,并将当前值插入堆中。
此为小顶堆
时间复杂度:O(Nlogk)
空间复杂度:O(N)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
//哈希表统计每个元素出现次数
Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
for (int num : nums) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}
// int[] 的第一个元素代表数组的值,第二个元素代表了该值出现的次数。
//这段代码创建了一个优先队列,队列中的数组元素会按照它们的第二个元素值从小到大进行排序
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
//遍历哈希表,次数一直和堆顶比较
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int num = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (queue.peek()[1] < count) {
queue.poll();
queue.offer(new int[]{num, count});
}
} else {
queue.offer(new int[]{num, count});
}
}
//取最后的最小堆,构建前k个高频元素
int[] ret = new int[k];
for (int i = 0; i < k; ++i) {
ret[i] = queue.poll()[0];
}
return ret;
}
}

备注:
1)PriorityQueue 默认的顺序是自然升序;
2)PriorityQueue内部使用的是堆排序,堆排序只会保证第一个元素是当前优先队列里最小(或者最大)的元素。
当使用迭代器遍历时,结果不会按序进行输出;若需要结果按序输出,则需要使用循环和poll()进行获取内容。
3)按逆序创建:创建一个PriorityQueue优先队列,其按逆自然顺序进行排序(从大到小,队头大队尾小)
//方式一
PriorityQueue que_min = new PriorityQueue(new Comparator() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
};
});
//方式二
PriorityQueue que = new PriorityQueue(Collections.reverseOrder());
//方式三
PriorityQueue que_max = new PriorityQueue((a, b) -> b - a);//此方式要求项目jdk版本在1.8及以上
2、桶
时间复杂度和空间复杂度都是O(N)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// 第一步:统计每个数字出现的次数(用 HashMap 存:数字 -> 次数)
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num,map.getOrDefault(num,0)+1);
}
// 第二步:找出现次数的最大值(用来确定桶的大小)
int mxCnt = 0;
for (int cnt : map.values()) {
mxCnt = Math.max(mxCnt,cnt);
}
// 第三步:创建“桶数组”(索引 = 出现次数,值 = 该次数对应的所有数字)
// 比如:次数=3的数字都放在 buckets[3] 里
List<Integer>[] buckets = new ArrayList[mxCnt + 1];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<>();
}
// 把数字按出现次数放进对应的桶里
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int num = entry.getKey(); // 数字
int cnt = entry.getValue(); // 出现次数
buckets[cnt].add(num); // 放进次数对应的桶
}
// 第四步:倒序遍历桶(从次数最多的桶开始),收集前 k 个数字
int[] ans = new int[k];
int idx = 0; // 结果数组的当前位置
// 从最大次数桶往最小次数桶遍历
for (int i = mxCnt; i >= 0; i--) {
// 遍历当前桶里的所有数字(都是出现次数为 i 的数字)
for (int num : buckets[i]) {
// 把数字放进结果数组,直到收集够 k 个
ans[idx++] = num;
// 如果已经收集了 k 个,直接返回结果
if (idx == k) return ans;
}
}
return ans;
}
}

288

被折叠的 条评论
为什么被折叠?



