面试题30.最小的k个数

题目:输入n个整数,找出其中最小的k个数,例如输入4,5,1,6,2,7,3,8 这8个数字,则最小的四个数字为1,2,3,4,

 

这道题是典型的TopK问题,剑指Offer提供了两种方法来实现,一种方法是parition方法,一种

方法是建立一个大小为k的堆进行topk求解

 

这里我们只解释第一种方法:

1.首先随机查找数组中一个元素作为一个基准,然后parition一次使得数组左边的元素小于基本,数组右边的元素大于基准。

2.此时将再将基准插入到数组适当的位置并返回该位置的索引。

3.如果索引index小于k-1则继续在[index+1,end]范围内进行parition,

4.如果索引index大于k-1则继续在[start,index-1]范围内进行pariton

5.直到index==k-1时候结束

 

代码实现如下:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int Partiton(int array[],int start,int end)
 5 {
 6     int i=start;
 7     int j=end;
 8     int k=0;
 9     int base=array[0];
10     while(i<j)
11     {
12         if(i<j&&base<=array[j])
13             j--;
14 
15         if(i<j)
16         {
17             array[i]=array[j];
18             i++;
19         }
20 
21         if(i<j&&base>array[i])
22             i++;
23 
24         if(i<j)
25         {
26             array[j]=array[i];
27             j--;
28         }
29     }
30 
31     array[i]=base;
32 
33     return i;
34 }
35 
36 int FindTopK(int array[],int start,int end,int k)
37 {
38     int startindex=start;
39     int endindex=end;
40     int index=Partiton(array,startindex,endindex);
41 
42 
43 
44     while(index!=k-1)
45     {
46         if(index>k-1)
47         {
48             endindex=index-1;
49             index=Partiton(array,startindex,endindex);
50         }
51         else
52         {
53             startindex=index+1;
54             index=Partiton(array,startindex,endindex);
55         }
56     }
57     return index;
58 }
59 
60 
61 int main()
62 {
63     int array[]={4,5,1,6,2,7,3,8};
64     int len=8;
65     int Index;
66     int k=4;
67     Index=FindTopK(array,0,len-1,k);
68 
69     cout<<"The Top K number is: ";
70     for(int i=0;i<Index+1;i++)
71     {
72         cout<<array[i]<<" ";
73     }
74     cout<<endl;
75     system("pause");
76     return 0;
77 }

运行截图:

posted @ 2015-08-30 17:05  vpoet  阅读(261)  评论(0编辑  收藏  举报