网站救助计划
1.为阅读体验,本站无任何广告,也无任何盈利方法,站长一直在用爱发电,现濒临倒闭,希望有能力的同学能帮忙分担服务器成本
2.捐助10元及以上同学,可添加站长微信lurenzhang888,备注捐助,网站倒闭后可联系站长领取本站pdf内容
3.若网站能存活下来,后续将会持续更新内容
题目描述
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:arr = [0,1,2,1], k = 1
输出:[0]
限制:
- 0 <= k <= arr.length <= 10000
- 0 <= arr[i] <= 10000
题解
(堆) O(n)
使用大根堆存储 k 个最小的数,怎么存呢,遍历每个数,先加到大根堆中,如果堆的大小大于 k 则弹出一个堆顶,所以数都遍历完后,此时堆中存的就是最小的 k 个数。
时间复杂度
O(n)
空间复杂度
O(n)
C++ 代码
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
priority_queue<int> heap;
for (auto x : arr) {
heap.push(x);
if (heap.size() > k)
heap.pop();
}
vector<int> res;
while (heap.size()) {
res.push_back(heap.top());
heap.pop();
}
return res;
}
};
Java 代码
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
for (int x : arr) {
heap.offer(x);
if (heap.size() > k)
heap.poll();
}
int[] res = new int[k];
int index = 0;
while (!heap.isEmpty()) {
res[index ++ ] = heap.poll();
}
return res;
}
}
Python 代码
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
heap = []
for x in arr:
heapq.heappush(heap, x)
res = []
for _ in range(k):
res.append(heapq.heappop(heap))
return res
本文由读者提供,Github地址:https://github.com/tonngw
点击面试手册,获取本站面试手册PDF完整版