快排的一次排序
牛客超时
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
int Partition(int low,int high, vector<int> input)
{
int pivot=input[0];
while(low<high)
{
while(low<high && input[high]<=pivot)
--high;
input[low]=input[high];
while(low<high && input[low]>=pivot)
++low;
input[high]=input[low];
}
input[low]=pivot;
return low;//返回基准最终的位置
}
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int start=0;
int length=input.size();
int end=length-1;
int pivotpos = Partition(start,end,input);
vector<int> leastNumbers;
if(pivotpos>k)//说明最小k个数在左边的序列中
{
end=pivotpos-1;
pivotpos=Partition(start,end,input);
}
else
{
start=pivotpos+1;
pivotpos=Partition(start,end,input);
}
copy(input.begin(),input.begin()+k,leastNumbers.begin());
return leastNumbers;
}
};
使用STL算法库中的push_heap(),pop_heap()等函数构建最大堆
牛客超时
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if(k>input.size()||input.size()==0 || k<0){
return res;
}
if(k==input.size()){
return input;
}
for(int i=0;i<k;i++){
res.push_back(input[i]);
push_heap(res.begin(), res.end());
//push_heap(res.begin(), res.end(), less<int>());
}
for(int i=k;i<input.size();i++){
if(res[0]>input[i]){
pop_heap(res.begin(), res.end());
res.pop_back();
res.push_back(input[i]);
push_heap(res.begin(), res.end());
}
}
return res;
}
};
使用优先队列构建最大堆
牛客超时
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if(k>input.size()||input.size()==0 || k<0){
return res;
}
if(k==input.size()){
return input;
}
priority_queue <int > queMax;
for(int i=0;i<k;i++){
queMax.push(input[i]);
}
for(int i=k;i<input.size();i++){
if(queMax.top()>input[i]){
queMax.pop();
queMax.push(input[i]);
}
}
while(!queMax.empty()){
res.push_back(queMax.top());
queMax.pop();
}
return res;
}
};