LeetCode最小的k个数

/************************************************************************ * Author : yqtao * Email :[email protected] * Date :2016.6.27 *************************************************************************/
#include <set>
#include<iostream>
#include<vector>
#include <functional>
using namespace std;
multiset<int,greater<int>> leastKNums(vector<int> &nums, int k)
{

    multiset<int, greater<int>> res;
    if (nums.size() < k)      
    {
        multiset<int, greater<int>>res(nums.begin(), nums.end()); 
        return res;
    }
    if (k < 1)
        throw "error";
    for (auto it = nums.begin(); it != nums.end();++it)  //遍历需要处理的数组
    {
        if (res.size() < k)
            res.insert(*it);
        else
        {
            auto iter = res.begin();//即k个数中的最大值
            if (*it < *iter)
            {
                res.erase(iter);
                res.insert(*it);
            }
        }
    }
    return res;
}
int main()
{
    vector<int>nums = { 1,2,3,4,5,6,7,8,9,3,2,4,6,7,6,56,4354,324, };
    multiset<int, greater<int>> res = leastKNums(nums, 10);
    for (auto c : res)
        cout << c << " " << endl;
    return 0;
}

你可能感兴趣的:(LeetCode)