剑指29:最小的k个数

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector <int> result;
        int len=input.size();
        if (input.empty() || k<=0 || len<k) return result;
        multiset<int, greater<int> >leastNumbers;
        multiset<int , greater<int >>::iterator iterGreater;
        
        vector <int>::iterator iter=input.begin();
        for (;iter!=input.end();++iter){
            if (leastNumbers.size()<k)
            {
                leastNumbers.insert(*iter);
            }
            else {
                iterGreater=leastNumbers.begin();
                if (*iter < *(leastNumbers.begin())){
                    leastNumbers.erase(iterGreater);
                    leastNumbers.insert(*iter);
                }
            }
        }
        for (iterGreater=leastNumbers.begin();iterGreater!=leastNumbers.end();++iterGreater)
        {
            result.push_back(*iterGreater);
        }
        return result;
        
    }
};
posted on 2020-08-03 21:51  滚雪球效应  阅读(105)  评论(0编辑  收藏  举报