剑指offer---最小的K个数

题目最小的K个数

要求:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        
    }
};

解题代码:

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> res;
        if(k <= 0 || k > input.size()) return res;

        int idx =0;
        while(idx < k){
            res.push_back(input[idx++]);
        }
        BubbleSort(res);

        for(; idx < input.size(); idx++){
            if(input[idx] < res[k-1])
                res[k-1] = input[idx];
            BubbleSort(res);
        }
        return res;
    }

private:
    void BubbleSort(vector<int> &array){
        bool flag = true;
        for(int i = 0; i < array.size() && flag; i++){
            flag = false;
            for(int j = array.size()-1; j > i; j--){
                if(array[j] < array[j-1]){
                    swap(array[j], array[j-1]);
                    flag = true;
                }
            }
        }
    }
};
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9951411.html