最小的k个数
题目要求:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
方法1,类似选择排序,不断寻找最小值
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(input.size() < k) return vector<int>();
vector<int> res;
for(int i = 0;i < k;i++) {
vector<int>::iterator iter = min_element(input.begin()+i, input.end());
res.emplace_back(*iter);
iter_swap(input.begin()+i, iter);
}
return res;
}
};
方法2,维护一个大小为k的最大堆
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(k <= 0 || input.size() < k) return vector<int>();
//建立最大堆
make_heap(input.begin(), input.begin()+k);
for(int i = k;i < input.size();i++) {
if(input[0] > input[i]){
swap(input[0], input[i]);
make_heap(input.begin(), input.begin()+k);
}
}
sort_heap(input.begin(), input.begin()+k);
vector<int> res(input.begin(), input.begin()+k);
return res;
}
};
方法3,类似快速排序,利用partition函数。
class Solution {
public:
int partition(vector<int>& vec, int low, int high) {
int i = low, j = high;
int pivot = vec[i];
while(i < j) {
while(i < j && vec[j] >= pivot) j--;
vec[i] = vec[j];
while(i < j && vec[i] <= pivot) i++;
vec[j] = vec[i];
}
vec[i] = pivot;
return i;
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(k <= 0 || input.size() < k) return vector<int>();
int low = 0, high = input.size()-1;
int h = partition(input, low, high);
while(h != k) {
if(h < k) {
low = h+1;
h = partition(input, low, high);
}
else {
high = h-1;
h = partition(input, low, high);
}
}
//sort(input.begin(), input.begin()+k);
vector<int> res(input.begin(), input.begin()+k);
return res;
}
};
方法4,set集合,采用红黑树。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(k <= 0 || input.size() < k) return vector<int>();
multiset<int> aset;
for(auto num : input) {
aset.insert(num);
}
vector<int> vec;
for(auto num : aset) {
vec.push_back(num);
}
vector<int> res(vec.begin(), vec.begin()+k);
return res;
}
};