[剑指 offer] JT29---the smallest number of K (beautiful boys and girls, come in and learn quickly!)

The topic is as follows

Insert picture description here

Idea and code

The sort() function solves thousands of worries, the interviewer does not want to look back

It’s very simple, it’s sorting and outputting. You must use fast sorting. The
interview question is whether it will be sorted quickly in the exam. If you sort by bubbling, the
interviewer may ask you,"We still lack cleaners here, are you interested?"
Quick row, C++ has encapsulated functions, let's see how easy it is to use functions?

class Solution {
    
    
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
    
    
        vector<int> ans;
        if(k>input.size()) return ans;
        sort(input.begin(),input.end());
        for(int i=0;i<k;i++){
    
    
            ans.push_back(input[i]);
        }
        return ans;
    }
};

Ten years of sharpening a sword, fast queue will always be the first (handwritten fast queue)

Use simple language to describe the quick
sort. Find a number greater than base from the left. Find a number
less than base from the right.
If the subscripts of the two numbers are different, exchange the two numbers.
This small number goes to the left.
When the two traverse to the same subscript, the subscript and base exchange, you can ensure that the number on the left of base is smaller than base, and the number on the right is larger than base, this is what we want!
Then just sort the top k numbers.
Here is a quick and detailed blog to recommend to everyone! ! !
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
Quick sort method (detailed explanation)

class Solution {
    
    
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
    
    
        int n=input.size();
        if(k>n) return vector<int>();
        quickSelect(input,0,n-1,k);
        return vector<int>(input.begin(),input.begin()+k);
    }
    void quickSelect(vector<int> &input,int left,int right,int k){
    
    
        if(left>=right) return ;
        int l=left,r=right,base=input[left];
        while(l<r){
    
    
            while(input[r]>=base&&l<r){
    
    
                r--;
            }
            while(input[l]<=base&&l<r){
    
    
                l++;
            }
            if(l<r){
    
    
                swap(input[l],input[r]);
            }
        }
        input[left]=input[l],input[l]=base;
        if(l>k-1){
    
    
            quickSelect(input,left,l-1,k);
            quickSelect(input,l+1,right,k);
        }
    }
    void swap(int &a,int &b){
    
    
        a^=b;
        b^=a;
        a^=b;
    }
};

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114847418