面试30 求数组中最小的k个数
来源:互联网 发布:node实战 编辑:程序博客网 时间:2024/04/30 02:46
#include<iostream>#include<cstdio>#include<cstdlib>#include<set>#include<functional>#include<algorithm>#include<ctime>using namespace std;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)//跳出循环时index=k-1 此时a[0] a[1]...a[k-1] 刚好为最小的k个数{ 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;}
其实最直观的做法就是对数组从小到大排序,然后取前k个数。时间复杂度取决于排序算法
mulitset<int,greater<int>()>
0 0
- 面试30 求数组中最小的k个数
- 求数组中最小的k个数
- 算法之求数组中最小的K个数
- 算法题:求数组中最小的k个数
- 求一个数组中最小的k个数
- 求一个数组中最小的K个数
- 求无序数组中最小的k个数
- 剑指offer-求数组中最小的k个数
- 算法面试题:求最小的k个束/求数组中最小的k个数
- 求数组中第k小的数,或者最小的k个数
- 数组中最小的K个数
- 数组中最小的k个数
- 无序数组中最小的k个数
- 找到数组中最小的K个数
- 无序数组中最小的K个数
- 无序数组中最小的k个数
- 找出数组中最小的 K 个数
- 无序数组中最小的k个数
- centos7 下安装Apache2+MariaDB+PHP5过程详解
- Qt中使用html语言对word进行图表操作
- poj 3280 字符串上的动态规划
- tablview性能优化&instrument详解
- 获得手势所在的图片坐标 & CGRectContainsPoint
- 面试30 求数组中最小的k个数
- HDU 4932/BC 4B Miaomiao's Geometry
- Shiro学习(19)动态URL权限限制
- 《图论》——最短路径 Dijkstra算法(戴克斯特拉算法)
- 1027. Colors in Mars (20)
- C语言计算某天是一年中的第几天(熟练使用状态位flag)
- CSS 整理(2)
- 关于火狐,IE,谷歌的主页遭到劫持的终极解决办法
- Ubuntu 14.04.2 系统无线网络不稳定问题