练习:最小的k个数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值