码迷,mamicode.com
首页 > 其他好文 > 详细

最小的k个数

时间:2015-07-09 18:01:10      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享

void GetLeastNumbers(int* input, int n, int* output, int k)
{
if (input == NULL || output == NULL || k > n || n <= 0 || k <= 0)
return;
int start = 0;
int end = n - 1;
int index = Partition(input, n, start, end);
while (index != k - 1)
{
if (index > k - 1)
{
end = index - 1;
index = Partition(input, n, start, end);
}
else
{
start = index + 1;
index = Partition(input, n, start, end);
}
}
for (int i = 0; i < k; ++i)
output[i] = input[i];
}

技术分享

技术分享

typedef multiset<int, greater<int>>  intSet;
typedef multiset<int, greater<int>>::iterator setIterator;
void GetLeastNumbers(const vector<int>& data, intSet& leastNumbers, int k)
{
leastNumbers.clear();
if (k < 1 || data.size() < k)
return;
vector<int>::const_iterator iter = data.begin();
for (; iter != data.end(); ++iter)
{
if ((leastNumbers.size()) < k)
leastNumbers.insert(*iter);
else
{
setIterator iterGreatest = leastNumbers.begin();
if (*iter < *(leastNumbers.begin()))
{
leastNumbers.erase(iterGreatest);
leastNumbers.insert(*iter);
}
}
}
}

技术分享

技术分享


版权声明:本文为博主原创文章,未经博主允许不得转载。

最小的k个数

标签:

原文地址:http://blog.csdn.net/wangfengfan1/article/details/46819191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!