最小的K个数(面试题 30)
来源:互联网 发布:透明软件 编辑:程序博客网 时间:2024/06/03 09:10
题目:输入n个整数,找出其中最小的k个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
#include "iostream"using namespace std;int partition(int array[],int low,int high){int pivot =array[low];while(low<high){while(low<high&&array[high]>=pivot) high--;array[low] =array[high];while(low<high&&array[low]<=pivot)low++;array[high] =array[low];}array[low] =pivot;return low;}//利用二分的思想,但是会修改数组内容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,start,end);while(index !=k-1){if (index>k-1){end =index -1;index =partition(input,start,end);}else{start =index +1;index =partition(input,start,end);}}for (int i=0;i<k;i++){output[i] =input[i];}}void main(){int array[8] ={3,5,1,6,2,7,0,8};int output[10];GetLeastNumbers(array,8,output,4);for (int i=0;i<4;i++){cout<<output[i]<<" ";}cout<<endl;}
0 0
- 面试题30:最小的k个数
- 面试题30 最小的K个数
- 面试题30:最小的K个数
- 面试题30 最小的K个数
- 面试题30:最小的K个数
- 面试题30:最小的k个数
- 面试题30:最小的K个数
- 面试题30:最小的k个数
- 面试题30最小的k个数
- 面试题30:最小的k个数
- 面试题30:最小的k个数
- 面试题 30 : 最小的K个数
- 最小的K个数(面试题 30)
- 面试题30:最小的k个数(未)
- 面试题26:最小的k个数
- 面试题:求最小的K个数。
- 面试题34:最小的K个数
- 面试题30.最小的K个数
- 4-0. 求符合给定条件的整数集(15)
- JPA(java persistence API)访问企业级信息
- UITableView 表视图
- rails 路由
- POJ 2253 Frogger
- 最小的K个数(面试题 30)
- SourceTree报错(RPC failed; result=56, HTTP code = 0)
- linux 内核编译
- 抽象类和接口
- Matlab中产生正态分布随机数的函数normrnd-----用来产生高斯随机矩阵
- C语言程序的存储区域和编译过程
- S5PV210——异常
- OWL
- Red hat防火墙配置