/*输入n个整数,找出其中最小的k个数,例如输入4,5,1,6,2,7,3,8这8个数字,则最小的四个数字是1,2,3,4*/
#include <iostream>
#include <set>
#include <vector>
using namespace std;
typedef multiset<int, greater<int> > intSet;
typedef multiset<int, greater<int> > :: iterator SetIterator;
void GetLeastkNum(const vector<int> &data, intSet &LeastNum, int k)
{
if(k < 1 || data.size() < k)
return;
vector<int> :: const_iterator iter = data.begin();
for(; iter != data.end(); ++iter)
{
if(LeastNum.size() < k)
{
LeastNum.insert(*iter);
}
else
{
if(*iter < *(LeastNum.begin()))
{
SetIterator iterGreast = LeastNum.begin();
LeastNum.erase(iterGreast);
LeastNum.insert(*iter);
}
}
}
}
//===============测试代码===========
void Test(char *testname, int *data, int n, int k, int *expectedresult)
{
if(testname != NULL)
cout << testname << " begins:" << endl;
vector<int> ivec;
for(int i = 0; i < n; ++i)
ivec.push_back(data[i]);
if(expectedresult == NULL)
cout << "The input is invalid, we don't expect any result." << endl;
else
{
for(int i = 0; i < k; ++i)
cout << expectedresult[i] << " ";
cout << endl;
}
intSet LeastNums;
GetLeastkNum(ivec, LeastNums, k);
for(SetIterator iter = LeastNums.begin(); iter != LeastNums.end(); ++iter)
cout << *iter << " ";
cout << endl;
}
//==========测试用例=========
//k小于数组长度
void Test1()
{
int data[] = {4, 5, 1, 6, 2, 7, 3 ,8};
int expectedresult[] = {1, 2, 3, 4};
Test("Test1", data, sizeof(data) / sizeof(int), sizeof(expectedresult) / sizeof(int), expectedresult);
}
//k等于数组长度
void Test2()
{
int data[] = {4, 5, 1, 6, 2, 7, 3 ,8};
int expectedresult[] = {1, 2, 3, 4, 5, 6, 7, 8};
Test("Test2", data, sizeof(data) / sizeof(int), sizeof(expectedresult) / sizeof(int), expectedresult);
}
//k大于数组的长度
void Test3()
{
int data[] = {4, 5, 1, 6, 2, 7, 3 ,8};
int *expectedresult = NULL;
Test("Test2", data, sizeof(data) / sizeof(int), 10, expectedresult);
}
//k等于1
void Test4()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int expectedresult[] = {1};
Test("Test4", data, sizeof(data) / sizeof(int), sizeof(expectedresult) / sizeof(int), expectedresult);
}
//k等于0
void Test5()
{
int data[] = {4, 5, 1, 6, 2, 7, 3 ,8};
int *expectedresult = NULL;
Test("Test2", data, sizeof(data) / sizeof(int), 0, expectedresult);
}
//数组中有相同的数字
void Test6()
{
int data[] = {4, 5, 1, 6, 2, 7, 2, 8};
int expectedresult[] = {1, 2};
Test("Test6", data, sizeof(data) / sizeof(int), sizeof(expectedresult) / sizeof(int), expectedresult);
}
//输入空指针
void Test7()
{
int *expectedresult = NULL;
Test("Test6", NULL, 0, 0, expectedresult);
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
最小的k个数
最新推荐文章于 2019-08-29 19:16:40 发布