zoukankan      html  css  js  c++  java
  • 剑指offer-面试题40-最下的k个数-快速排序

    /*
    题目:
    	输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
    */
    /*
    思路:
    	快速排序,找到第k+1大的数,其左边则为最小的k个数。
    */
    #include<iostream>
    #include<string.h>
    #include<stdio.h>
    #include<set>
    #include<vector>
    
    using namespace std;
    
    void core(vector<int> &input,int k,int beginIndex, int endIndex){
        int last = endIndex;
        int val = input[endIndex];
        for(int i = endIndex-1; i >= beginIndex; i--){
            if(input[i] > val){
                swap(input[i],input[last]);
                last--;
            }
        }
        if(last+1 < k){
            core(input,k,last+1,endIndex);
        }else if(last+1 > k){
            core(input,k,beginIndex,last-1);
        }
    }
    
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> out;
        if(input.empty() || k == 0) return out;
        core(input,k,0,input.size()-1);
        for(int i = 0; i < k ;i++){
            out.push_back(input[i]);
        }
        return out;
    }
    
    int main(){
        vector<int> in = {4,5,1,6,2,7,3,8};
        vector<int> out = GetLeastNumbers_Solution(in,4);
        for(int i = 0; i < out.size(); i++){
            cout<<out[i]<<" ";
        }
    
    }
    

       

  • 相关阅读:
    mysql常用命令
    CSS样式
    定位
    background
    文本属性和字体属性
    超链接导航案例
    margin塌陷
    浮动
    GIT 修改提交地址
    VUE ElementUI 表格多选框实现单选
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11979595.html
Copyright © 2011-2022 走看看