题目描述
给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。如果K>数组的长度,那么返回一个空的数组
冒泡排序
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> vec;
int len = input.size();
if(k > len) return vec;
int flag;
//冒泡排序
for(int i=0 ; i<k ; i++){
flag = 0;
for(int j=0 ; j<len-1-i ; j++){
if(input[j] < input[j+1]){
flag = j;
int t = input[j];
input[j] = input[j+1];
input[j+1] = t;
}
}
vec.push_back(input[len-1-i]);
if(flag == 0) break;
i = len-flag-2;
}
while(vec.size() != k){
vec.push_back(input[len-1-vec.size()]);
}
return vec;
}
};
插入排序
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> vec;
if(k > input.size()) return vec;
int i=0;
for(i=0 ; i<input.size() ; i++)
{
int len = vec.size();
int val = input[i];
int j = len-1;
if(len < k)
vec.push_back(val);
while(j>=0 && vec[j] > val)
{
vec[j+1] = vec[j];
j--;
}
if(j != len-1)
{
vec[j+1] = val;
}
}
return vec;
}
};