剑指offer(29)—最小的K个数

来源:互联网 发布:奥米姿淘宝 编辑:程序博客网 时间:2024/05/23 19:18

最小的K个数

题目描述

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

思路

解法1:利用Partition函数,第k个位置前面的数就是最小的k个数
解法2:建立一个大小为k的容器,想填满该容器,并确定出其中的最大值,读取下一个数时,若大于最大值,则继续读取下一个数;否则,替换当前最大值,并重新确定调整后的容器中的最大值,继续读取下一个数,时刻保持容器中存储的是当前为止的最小的k个数。(最大堆)
解法3:红黑树,利用STL中的set或multiset

代码

解法1:

class Solution {public:    int Partition(vector<int>& nums, int start, int end){        int key = nums[start];        while(start < end){            while(start < end && nums[end] >= key)                end--;            swap(nums[start], nums[end]);            while(start < end && nums[start] <= key)                start++;            swap(nums[start], nums[end]);        }        return start;    }    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {        int len = input.size();        vector<int> res;        if(len == 0 || k <= 0 || k > len)            return res;        int start = 0, end = len - 1;        int index = Partition(input, start, end);        while(index != (k-1)){            if(index > k-1){                end = index - 1;                index = Partition(input, start, end);            }else{                start = index + 1;                index = Partition(input, start, end);            }        }        for(int i = 0; i < k; i++)            res.push_back(input[i]);        return res;    }};