面试100题:6.求上排数字在下排出现的次数

解析一道腾讯公司的面试题,要求根据上排给定的十个数字,在下排填出这些数字出现的次数,通过C++实现解决方案。

题目

腾讯面试题--给你10分钟时间,根据上排给出十个数,求在其下排填出对应的十个数,要求下排每个数都是先前上排那十个数在下排出现的次数。 

上排的十个数如下: 

【0,1,2,3,4,5,6,7,8,9】

初看此题,貌似很难,10分钟过去了,可能有的人,题目都还没看懂。 

举一个例子, 

数值:0,1,2,3,4,5,6,7,8,9 

分配:6,2,1,0,0,0,1,0,0,0 

0在下排出现了6次,1在下排出现了2次, 

2在下排出现了1次,3在下排出现了0次.... 

以此类推.

  1. /*Title: 6.求上排数字在下排出现的次数 
  2. Author:  gocode 
  3. Date:    2012-10-04*/  
  4.   
  5. #include <iostream>  
  6. using namespace std;  
  7. #define len 10  
  8.   
  9. // 定义求解的类NumberTB  
  10. class NumberTB  
  11. {  
  12. private:  
  13.     int bottom[len]; // 下排数字数组  
  14.     bool success;  
  15. public:  
  16.     NumberTB();  
  17.     int round;  
  18.     int top[len]; // 上排数字数组  
  19.     int* getBottom();  
  20.     void setNextBottom();  
  21.     int getFrequency(int num);  
  22. };  
  23.   
  24. // 构造函数  
  25. NumberTB::NumberTB()  
  26. {  
  27.     success = false;  
  28.     for(int i = 0; i < len; i++)  
  29.         top[i] = i;  
  30. }  
  31.   
  32. // 求下排数字  
  33. int* NumberTB::getBottom()  
  34. {  
  35.     round = 0;  
  36.     while(!success)  
  37.     {  
  38.         round++;  
  39.         setNextBottom();  
  40.     }  
  41.     return bottom;  
  42. }  
  43.   
  44. void NumberTB::setNextBottom()  
  45. {  
  46.     bool reB = true;  
  47.     for(int i = 0; i < len; i++)  
  48.     {  
  49.         int frequency = getFrequency(i);  
  50.         if(bottom[i] != frequency)  
  51.         {  
  52.             bottom[i] = frequency;  
  53.             reB = false;  
  54.         }  
  55.     }  
  56.     success = reB;  
  57. }  
  58.   
  59. int NumberTB::getFrequency(int num)  
  60. {  
  61.     int count = 0;  
  62.     for(int i = 0; i < len; i++)  
  63.     {  
  64.         if(bottom[i] == num)  
  65.             count++;  
  66.     }  
  67.     return count;  
  68. }  
  69.   
  70. int main()  
  71. {  
  72.     NumberTB nTB;  
  73.     int* up = nTB.top;  
  74.     for(int j = 0; j< len; j++) // 打印上排数组  
  75.         cout<<*up++<<" ";  
  76.    
  77.     cout<<endl;  
  78.     int* result = nTB.getBottom();  
  79.     for(int i = 0; i < len; i++) // 打印下排数组  
  80.         cout<<*result++<<" ";  
  81.    
  82.     cout<<endl;  
  83.     cout<<"Run round: "<<nTB.round<<endl;  
  84.    
  85.     getchar();  
  86.     return 0;  
  87. }  
结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值