题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

C++代码:

class Solution {
public:
    //使用优先级队列
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> res;
        if(input.size()<k) return res;
        if(input.size()==k) return input;
        priority_queue<int, vector<int>, greater<int>> Q;
        for(int i=0;i<input.size();i++)
            Q.push(input[i]);
        for(int i = 0;i<k;i++)
        {
            res.push_back(Q.top());
            Q.pop();
        }
        return res;
    }
};
class Solution {
public:
  //使用STL的sort排序
    vector<int> GetLeastNumbers_Solution2(vector<int> input, int k) {
        vector<int> res;
        if(input.size()<k) return res;
        if(input.size()==k) return input;
        sort(input.begin(),input.end());
        for(int i=0;i<k;i++)
            res.push_back(input[i]);
         
        return res;
    }
};
//堆排序思想
class Solution {
private:
     void heapSort(vector<int> &input, int root, int end){
        for(int j = end -1; j >= root; j --){
            int parent = (j + root -1)/2;
            if(input[parent] > input[j]){
                int temp = input[j];
                input[j] = input[parent];
                input[parent] = temp;
            }
        }  
     }
     
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> result ;
        if(k > input.size()) return result;
        for(int i = 0; i < k ; i ++){
            heapSort(input,i,input.size());
            result.push_back(input[i]);
        }
        return result;
    }
};