您的位置:首页 > 职场人生

面试题30 最小的K个数

2015-08-27 15:08 375 查看
思路:最直观的想法就是先排序再取前k个数,这种方法的时间复杂度取决于排序的算法。用partition()
函数找枢纽元素,是元素下标为k-1
//适合数据量比较大的算法:用multiset<intgreater<int>>
容器存储k个变量并实时更新里面的元素
函数接口:void GetLeastKNumber(int *a,int length,multiset<int,greater<int>>&leastNumbers,int k);

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<set>
#include<functional>
#include<algorithm>
#include<ctime>
using namespace std;
//面试题30 最小的K个数   思路:最直观的想法就是先排序再取前k个数,这种方法的时间复杂度取决于排序的算法。用partition() 函数找枢纽元素,是元素下标为k-1
//适合数据量比较大的算法:用multiset<int greater<int>> 容器存储k个变量并实时更新里面的元素
int Partition(int *a,int start,int end)
{
int i=start,j=end;
int key=a[i];
while(i<j)
{
while(i<j&&a[j]>=key)
{
j--;
}
if(i<j)
{
a[i]=a[j];
i++;
}
while(i<j&&a[i]<=key)
{
i++;
}
if(i<j)
{
a[j]=a[i];
}
}
a[i]=key;
return i;
}
//以下方法时间复杂度为O(n)
void GetLeastNumbers(int *input,int n,int *output,int k)//找出数组中最小的k个数
{
int start=0,end=n-1;
int index=Partition(input,start,end);
while(index!=k-1)
{
if(index>k-1)
{
end=index-1;
index=Partition(input,start,end);
}
else if(index<k-1)
{
start=index+1;
index=Partition(input,start,end);
}
}
cout<<"the "<<k<<"least number is:"<<endl;
for(int i=0;i<k;i++)
{
output[i]=input[i];
cout<<output[i]<<" ";
}
cout<<endl;
}
//比较适合处理海量的数据 时间复杂度为o(logk)
void GetLeastNumbers2(int *input,int n,multiset<int ,greater<int>>&LeastSet,int k)//找出数组中最小的k个数存到set中
{
for(int i=0;i<n;i++)
{
if(LeastSet.size()!=k)
{
LeastSet.insert(input[i]);
}
else
{
multiset<int,greater<int>>::iterator iter=LeastSet.begin();
if(*iter>input[i])
{
LeastSet.erase(iter);
LeastSet.insert(input[i]);
}
}
}
cout<<"the "<<k<<"least number is:"<<endl;
multiset<int,greater<int>>::iterator iter=LeastSet.begin();
for(;iter!=LeastSet.end();iter++)
{
cout<<*iter<<" ";
}
cout<<endl;
}
int main()
{

srand(time(NULL));
int a[10],output[10];
multiset<int,greater<int>> testSet;
cout<<"the original numbers is:"<<endl;
for(int i=0;i<10;i++)
{
a[i]=rand()%100;
cout<<a[i]<<"  ";
}
cout<<endl;
GetLeastNumbers(a,10,output,4);
GetLeastNumbers2(a,10,testSet,4);//找出数组中最小的k个数
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: