关闭

最小的k个数

310人阅读 评论(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);
}
}
}
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:156108次
    • 积分:6149
    • 等级:
    • 排名:第4029名
    • 原创:479篇
    • 转载:2篇
    • 译文:1篇
    • 评论:3条
    最新评论