zoukankan      html  css  js  c++  java
  • 面试题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 }

    运行截图:

  • 相关阅读:
    OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django'
    mac 安装pip
    同学公司倒闭了
    web开发中的字体选择(同事分享)
    svg 学习笔记
    用highchaarts做股票分时图
    highcharts,highStock 中文图表配置
    为什么使用 npm Scripts 构建项目
    JS 浮点型计算的精度问题 推荐的js 库 推荐的类库 Numeral.js 和 accounting.js
    HTML代码转换为JavaScript字符串
  • 原文地址:https://www.cnblogs.com/vpoet/p/4771160.html
Copyright © 2011-2022 走看看