面试题40:最小的K个数

一:先排序,取前k个数

class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
        vector<int>res;
        if(arr.size()==0)return res;
        sort(arr.begin(),arr.end());
        for(int i=0;i<k;++i)
           res.push_back(arr[i]);
        return res;
    }
};

二:使用容器(multiset)固定k个位,当容器未满时,可插入;满时,与容器内最大比较,如果比最大的小,就删除最大的,插入新元素

#include
#include
#include
using mul=std::multiset<int, std::greater<int>>;
using setvit=std::multiset<int, std::greater<int>>::iterator;


void GetLastNumbers(std::vector<int>& arr, mul& leastNumbers, size_t k)
{
	if (k < 1 || arr.size() < k)return;
	std::vector<int>::iterator vit = arr.begin();
	for (;vit != arr.end();++vit)
	{
		if (leastNumbers.size() < k)
		{
			leastNumbers.insert(*vit);
		}
		else
		{
			setvit isGreatest = leastNumbers.begin();
			if (*vit < *isGreatest)
			{
				leastNumbers.erase(isGreatest);
				leastNumbers.insert(*vit);
			}
		}
	}
}

int main()
{
	std::vector<int> arr = { 9,8,6,4,15,1,2,7 };
	mul leastNumbers;
	GetLastNumbers(arr, leastNumbers, 3);
	for (auto num : leastNumbers)
	{
		std::cout << num << " ";
	}
	std::cin.get();
	return 0;
}

你可能感兴趣的:(C++剑指Offer刷题集)