牛客网剑指offer-最小的K个数

题目描述

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


方法1:

class Solution {
public:
    //因为最小的K个数不要求排序输出,最快的办法是用类似快排的方法,用二分找出分界点,而不需要全部排序完
    vector GetLeastNumbers_Solution(vector input, int k) {
        vector ans;
        if (input.size() == 0 || input.size() < k)
            return ans;
        int start = 0, end = input.size()-1;
        while (true)
        {
            int mid = partition(input, start, end);
            //找到了分界点
            if (mid == k)
            {
                for (int i = 0; i < k; ++i)
                    ans.push_back(input[i]);
                return ans;
            }
            //分界点在左边
            else if (mid > k)
                end = mid - 1;
            //分界点在右边
            else
                start = mid + 1;
        }
    }
private:
    //快排的partition
    int partition(vector &array, int start, int end)
    {
        if (start == end)
            return start;
        int x = array[start];
        while (start < end)
        {
            while (start < end)
            {
                if (array[end] >= x)
                    --end;
                else
                {
                    array[start++] = array[end];
                    break;
                }
            }
            while (start < end)
            {
                if (array[start] < x)
                    ++start;
                else
                {
                    array[end--] = array[start];
                    break;
                }
            }
        }
        array[start] = x;
        return start;
    }
};

方法2:

class Solution {
public:
    //如果要求不能改变原数组的话就可以使用最大堆或者红黑树来维护最小的K个数
    vector GetLeastNumbers_Solution(vector input, int k) {
        vector ans;
        if (input.size() == 0 || input.size() < k || k < 1)
            return ans;
        for (int i = 0; i < k; ++i)
            ans.push_back(input[i]);
        make_heap(ans.begin(), ans.end());
        for (int i = k; i < input.size(); ++i)
        {
            if (ans[0] > input[i])
            {
                pop_heap(ans.begin(), ans.end());
                ans.pop_back();
                ans.push_back(input[i]);
                push_heap(ans.begin(), ans.end());
            }
        }
        return ans;
    }
};


你可能感兴趣的:(剑指offer)