Sword finger offer -- the minimum number of k

Title:

Enter n integers to find the smallest number of K. For example, if you enter 8 numbers of 4,5,1,6,2,7,3,8, the minimum 4 numbers are 1,2,3,4,.

Analysis:

Generally speaking, there are two solutions.

Solution 1: sort() is used to sort the input data. The method is simple, applicable to small amount of data, and will change the input array.

Use of sort(): sort(begin,end,compare). Compare is the set sorting method. The default is from small to large.

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

Solution 2: Based on the implementation of red black tree or heap, it is suitable for massive data and does not change the input array.

Based on the red black tree implementation, using multiset implementation (unavailable set, set will be de duplicated).

Usage of multiset: [C++ STL] Set and Multiset

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> ans;
        if(input.size()==0||k<=0||k>input.size())
            return ans;
        multiset<int> mse;
        for(auto it=input.begin();it!=input.end();mse.insert(*it++));
        for(auto it=mse.begin();k--;ans.push_back(*it++));
        return ans;
    }
};

Based on the heap implementation, the priority queue implementation is used.

Usage of priority queue: priority_queue

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> ans;
        if(input.size()==0||k<=0||k>input.size())
            return ans;
        priority_queue<int,vector<int>,greater<int> > que;
        for(auto it=input.begin();it!=input.end();que.push(*it++));
        for(;k--;ans.push_back(que.top()),que.pop());
        return ans;
    }
};

 

Posted by Ting on Tue, 31 Dec 2019 04:39:43 -0800