title: Daily practice (21): the smallest number of k
categories:[Swords offer]
tags:[Daily practice]
date: 2022/02/17
Daily practice (21): the smallest number of k
Enter the integer array arr and find the smallest k numbers in it. For example, if you enter 8 numbers 4, 5, 1, 6, 2, 7, 3, and 8, the smallest 4 numbers are 1, 2, 3, and 4.
Example 1:
Input: arr = [3,2,1], k = 2
Output: [1,2] or [2,1]
Example 2:
Input: arr = [0,1,2,1], k = 1
output: [0]
limit:
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
Source: LeetCode
Link: https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof
Method 1: sort sort
Ideas and Algorithms
Sort the original array from small to large and take out the first k numbers.
Complexity Analysis
- Time complexity: O(n logn), where n is the length of the array arr. The time complexity of the algorithm is the time complexity of sorting.
- Space complexity: O(logn), the additional space complexity required for sorting is O(logn).
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> ans(k, 0);
if (arr.size() == 0 || k == 0) {
return ans;
}
sort(arr.begin(), arr.end()); //排序
for (int i = 0; i < k; i++) {
ans.push_back(arr[i]); //添加到目标vector
}
return ans;
}
Method 2: Heap
Ideas and Algorithms
We use a large root heap to maintain the first k small values of the array in real time. First insert the first k numbers into the big root heap, and then traverse from the k+1th number. If the current traversed number is smaller than the number at the top of the big root heap, put the
The number at the top of the heap is popped, and then the number currently traversed is inserted. Finally, store the number in the big root heap into the array and return it. In the following code, since the heap (ie, the priority queue) in the C++ language is a big root heap, we can
what to do. The heap in the Python language is a small root heap, so we need to take the inverse of all the numbers in the array in order to use the small root heap to maintain the first k small values.
Complexity Analysis
- Time complexity: O(n logk), where nn is the length of the array arr. Since the big root heap maintains the first k small values in real time, insertion and deletion are O(logk) time complexity. In the worst case, n numbers in the array will be inserted, so a total of O(nlogk) time complexity is required.
- Space complexity: O(k), because there are at most k numbers in the big root heap.
vector<int> getLeastNumbers(vector<int>& arr, int k) {
vector<int> ans(k, 0);
if (arr.size() == 0 || k == 0) {
return ans;
}
priority_queue<int> q;
for (int i = 0; i < k; ++i) { //将前k个数插入堆中
q.push(arr[i]);
}
for (int i = 0; i < (int)arr.size(); ++i) {
if (q.top() > arr[i]) { //第 k+1 个数开始遍历,如果当前遍历到的数比大根堆的堆顶的数要小,就把
q.pop(); //堆顶的数弹出,再插入当前遍历到的数
q.push(arr[i]);
}
}
for (int i = 0; i < k; ++i) {
ans[i] = q.top(); //把堆中的数存到目标vector中
q.pop();
}
return ans;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。