/* 题目: 输入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]<<" "; } }