Topic description
Enter n integers and find the smallest K number among them. For example, if you enter 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4.
Problem solving ideas
Referring to the idea of divide and conquer in quick sort, first call the Partition function to find the subscript m of the divide and conquer point. If m is equal to k, the number of m before m is the solution; if m is less than k, continue to find the right side of m. Divide and conquer point; if m is greater than k, continue to find the divide and conquer point on the left of m until m and k are equal.
code
1 class Solution { 2 public: 3 vector<int> GetLeastNumbers_Solution(vector<int> &input, int k) { 4 vector<int> v; 5 int l=input.size(); 6 if(input.empty()||k<1||k>l) 7 return v; 8 if(k==l) 9 return input; 10 int m=Partition(input,0,l-1); 11 while(m!=k){ 12 if(m<k) 13 m=Partition(input,m+1,l-1); 14 else 15 m=Partition(input,0,m-1); 16 } 17 for(int i=0;i<m;i++) 18 v.push_back(input[i]); 19 return v; 20 } 21 int Partition(vector<int> &a, int f, int l) { 22 int i = f - 1; 23 for (int j = f; j < l; j++) 24 { 25 if (a[j] <= a[l]) { 26 i++; 27 swap(a[i], a[j]); 28 } 29 } 30 i++; 31 swap(a[i], a[l]); 32 return i; 33 } 34 };