K minimum number (18)

topic

Input [n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is 4, 3, 4]


Method 1: Sorting
directly to sort the array, and k values that satisfy the former requirement. However, this method, when a lot of data, inefficient.
Code:

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

Method two: the maximum stack
1, analysis:
first create a container can be put k elements, k values prior to input into the first vessel. Then k + 1 after the element are comparable to the elements in the container. If the container is greater than the maximum value, the input is discarded; if less than the maximum value of the container, it is replaced with the maximum value for the container.
This method does not require all the data once loaded into memory, the mass of the input data, it has a great advantage.
2, Code:

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        int len=input.size();
        // 注意处理意外情况
        if(len<=0 || k<=0 ||k>len)
            return vector<int>();
        //将input容器中的前k个元素存入一个新容器中
        vector<int> res(input.begin(),input.begin()+k);
        //创建堆
        make_heap(res.begin(),res.end());
        for(int i=k;i<len;++i)
        {
            //如果堆中的最大值大于输入容器中的值,则将其进行替换
            if(res.front()>input[i])
            {
                pop_heap(res.begin(),res.end());
                res.pop_back();
                res.push_back(input[i]);
                push_heap(res.begin(),res.end());
            }
        }
        sort_heap(res.begin(),res.end());
        return res;
    }
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104688539