zoukankan      html  css  js  c++  java
  • 剑指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;
                    }
                }
            }
        }
    };
  • 相关阅读:
    监听器
    过滤器
    连接池与分页
    jdbc优化
    jdbc入门
    web开发mysql基础
    自定义标签
    jsp基础
    会话管理入门
    19. Remove Nth Node From End of List C++删除链表的倒数第N个节点
  • 原文地址:https://www.cnblogs.com/iwangzhengchao/p/9951411.html
Copyright © 2011-2022 走看看