The smallest k number in Q40 array

The smallest k number in the array

topic

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

Ideas

Idea 1:

Use the fast-sorting partition function to initially sort the array, so that the arrays around k-1 are sorted.

Output the first k digits.

Idea 2:

When dealing with massive amounts of data, you can use a multi-set of k elements with the largest number on top to continuously judge whether to update the number in the set.

achieve

class Solution {
public:
    int partition(vector<int>& numbers, int left, int right)
    {
        if(numbers.empty() || left<0 || right>=numbers.size() || left>right)
            return -1;
        int pivot = numbers[left];
        while(left<right)
        {
            while(left<right && numbers[right]>=pivot)
                --right;
            numbers[left] = numbers[right];
            while(left<right && numbers[left]<=pivot)
                ++left;
            numbers[right] = numbers[left];
        }
        numbers[left] = pivot;
        return left;
    }
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> result;
        if(input.empty() || k<=0 || input.size()<k)
            return result;
        int left = 0;
        int right = input.size()-1;  //记得是减1
        int pindex = partition(input, left, right);
        int mark = k-1;
        while(pindex!=mark)
        {
            if(pindex<mark)
            {
                left = pindex+1;
                pindex = partition(input, left, right);
            }
            else
            {
                right = pindex-1;
                pindex = partition(input, left, right);
            }
        }
        for(int i=0; i<k; ++i)
            result.push_back(input[i]);
        return result;
    }
};
Published 58 original articles · won 11 · 30,000+ views

Guess you like

Origin blog.csdn.net/mhywoniu/article/details/105606288