Company BDui 面试 笔试 : 从10个已按从大到小排列好的数组中,求top 15个最大的数

来源:互联网 发布:淘宝一元换购怎么做 编辑:程序博客网 时间:2024/05/01 12:45
/* 
 * File:   bai  D company: 从10个已按从大到小排列好的数组中,求top 15个最大的数
 * Author: hongbin
 */


#include <cstdlib>
#include <iostream>
#include <vector>
#include<algorithm> 
using namespace std;


//array must be descending sorted when initialized. 
#define ARRAYNUM 10 //how many arrays whose values are sorteded descendingly
#define SIZE 10  //how many elements per an array
#define TOPNUM 15  //top 15 biggest numbers are listed


struct Current_Index{
int value;    
int ArrayIndex;
};


int data[ARRAYNUM][SIZE];


std::vector<int> HeadData; //save selected TOPNUM of values  


//element in an array  must be descending sorted, the first element is biggest. 
void InitData(){
 int i=0;
 int j=0;
    
 for(int i=0;i<ARRAYNUM;i++)
 for(int j=0;j<SIZE;j++) {
       data[i][j]=i*10-j;
    }
return;    
}


void export_topbig_data(){
  int index=0;
    int output_data;
    Current_Index myArrayIndex[ARRAYNUM];
    std::vector<int>::iterator myiter;
      //10 array index for 10 array, one to one
    //point to the first biggest element of each array
     for(int i=0;i<ARRAYNUM;i++) {
       myArrayIndex[i].ArrayIndex=0;
       myArrayIndex[i].value=data[i][0];
  //把每个队列的最前面的那个数字放到堆里面去。
       HeadData.push_back(data[i][0]);
    }
    //STL中关于heap默认调整成的是大顶堆: 即最前面的数值最大:
   make_heap(HeadData.begin(),HeadData.end());
   while( index < TOPNUM ) {
    //export current biggest data from the top of heap 
    output_data=HeadData.front();
    cout<<"Pop "<<index<<"th"<<" data: "<<output_data<<endl;
    /*
     input: 20 3 35 5 45
     make_heap后: 45 20 35 5 3 //the first is big one
     然后pop_heap: 35 20 3 5 45; //注意,pop_heap不是删除了45,而是把45挪到尾部来了,保证剩余的数 35 20 3 5是个大堆。   
     *  
     */
    pop_heap(HeadData.begin(),HeadData.end());  
    //remove this top data from vector 
    myiter=find(HeadData.begin(),HeadData.end(),output_data);
    
    if(myiter != HeadData.end())
    HeadData.erase(myiter);    
    //find which sub array includes this data
    for(int i=0;i<ARRAYNUM;i++ ) {
         if( myArrayIndex[i].value==output_data) {
           //push the next biggest data of this array into heap 
            myArrayIndex[i].ArrayIndex+=1;
            if( myArrayIndex[i].ArrayIndex < SIZE ) { 
              myArrayIndex[i].value=data[i][myArrayIndex[i].ArrayIndex];
              HeadData.push_back(myArrayIndex[i].value);
            }
            //re-make heap
            push_heap(HeadData.begin(),HeadData.end());            
            break;
        }   
      }
    index++;    
   }
   
   return;
}


int main(int argc, char** argv) {
       
    InitData();
    export_topbig_data();
  
  return 0;
}
0 0