首页 > 其他 > 详细

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

时间:2018-11-13 12:07:26      阅读:170      评论:0      收藏:0      [点我收藏+]

题目最小的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;
                }
            }
        }
    }
};

 

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

原文:https://www.cnblogs.com/iwangzhengchao/p/9951411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!