题目描述
1 class Solution {
2 public:
3 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
4 vector<int> res;
5 if(k<=0||k>input.size()) return res;
6 sort(input.begin(),input.end());
7 for(int i=0;i<k;i++)
8 {
9 res.push_back(input[i]);
10 }
11 return res;
12 }
13 };
法二:快排partition方法,算法复杂度O(klongN)
#include<iostream>
#include<vector>
using namespace std;
int partition(vector<int>& input, int begin, int end)
{
int low = begin;
int high = end;
int pivot = input[low];
while (low<high)
{
while (low<high&&pivot<=input[high])
{
high--;
}
if(low<high) input[low] = input[high];
while (low<high&&pivot>input[low])
{
low++;
}
if(low<high) input[high] = input[low];
}
input[low] = pivot;
return low;
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if (k <= 0 || k>input.size()) return res;
if (k == input.size()) return input;
int start = 0;
int end = input.size() - 1;
int index = partition(input, start, end);
while (index != k - 1)
{
//k个数有部分在右半边
if (index<k - 1)
{
start = index + 1;
index = partition(input, start, end);
}
//k个数都在左半边
else if (index>k - 1)
{
end = index - 1;
index = partition(input, start, end);
}
}
for (int i = 0; i<k; i++)
res.push_back(input[i]);
return res;
}
int main()
{
int a[] = {1,2,3,9,4};
vector<int> temp(a,a+5);
vector<int> res=GetLeastNumbers_Solution(temp,4);
for (int i = 0; i < 4; i++)
cout << res[i]<<endl;
}
法三:利用STL堆heap的算法
1 class Solution {
2 public:
3 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
4 if(k<=0||k>input.size()||input.size()<0) return vector<int> ();
5 vector<int> res(input.begin(),input.begin()+k);
6 make_heap(res.begin(),res.end());//此时res[0]为最大值,大顶堆
7 for(int i=k;i<input.size();i++)
8 {
9 if(input[i]<res[0])
10 {
11 //先删除最大的
12 pop_heap(res.begin(),res.end());
13 res.pop_back();
14 //再加入
15 res.push_back(input[i]);
16 push_heap(res.begin(),res.end());
17 }
18 }
19 return res;
20 }
21 };
法四:用STL容器
1 class Solution {
2 public:
3 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
4 if(k<=0||k>input.size()) return vector<int> ();
5 //vector<int> res;
6 multiset<int,greater<int>> Myset(input.begin(),input.begin()+k);
7 for(int i=k;i<input.size();i++)
8 {
9 multiset<int,greater<int>>::iterator iter=Myset.begin();
10 if(input[i]<*iter)
11 {
12 Myset.erase(iter);
13 Myset.insert(input[i]);
14 }
15 }
16 return vector<int>(Myset.begin(),Myset.end());
17 }
18 };