剑指offer:最小的K个数

时间:2022-12-01 18:58:15


题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

方法一

O(n)

改变输入,适合小数据

class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {

int len = input.size();
vector<int> res;

//注意k<=0的异常输入
if (k <= 0 || len < k){
return res;
}

int left = 0, right = len - 1;
int index = partition(input, left, right);

while (index != k - 1){
if (index < k - 1){
left = index + 1;
index = partition(input, left, right);
}
else{
right = index - 1;
index = partition(input, left, right);
}
}

for (int i = 0; i <= k - 1; i++){
res.push_back(input[i]);
}

return res;
}
private:
int partition(vector<int> &input, int left, int right){
int i = left, j = right;
int pivot = input[i];

while (i < j){
while (i<j && input[j]>pivot) j--;
if (i < j){
input[i++] = input[j];
}

while (i < j&&input[i] <= pivot) i++;
if (i < j){
input[j--] = input[i];
}
}

input[i] = pivot;

return i;
}

};

方法二

大顶堆,适合于大数据情形

class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {

vector<int> res;

int len = input.size();

if (k <= 0 || k > len){
return res;
}

priority_queue<int> heap;

for (int i = 0; i < len; i++){
if (heap.size() < k){
heap.push(input[i]);
}
else{
if (input[i] < heap.top()){
heap.pop();
heap.push(input[i]);
}
}
}


while (!heap.empty()){
res.push_back(heap.top());
heap.pop();
}

return res;
}
};