最小的k个数

25 篇文章 0 订阅
21 篇文章 0 订阅

快排的一次排序
牛客超时

#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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值