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

来源:互联网 发布:泰坦尼克号细节知乎 编辑:程序博客网 时间:2024/05/22 12:15

转载并参考July的博客http://topic.csdn.net/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9.html,万分感谢!

题目

腾讯面试题--给你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次.... 

以此类推.

/*Title: 6.求上排数字在下排出现的次数Author:  gocodeDate:    2012-10-04*/#include <iostream>using namespace std;#define len 10// 定义求解的类NumberTBclass NumberTB{private:    int bottom[len]; // 下排数字数组    bool success;public:    NumberTB();    int round;    int top[len]; // 上排数字数组    int* getBottom();    void setNextBottom();    int getFrequency(int num);};// 构造函数NumberTB::NumberTB(){    success = false;    for(int i = 0; i < len; i++)        top[i] = i;}// 求下排数字int* NumberTB::getBottom(){    round = 0;    while(!success)    {        round++;        setNextBottom();    }    return bottom;}void NumberTB::setNextBottom(){    bool reB = true;    for(int i = 0; i < len; i++)    {        int frequency = getFrequency(i);        if(bottom[i] != frequency)        {            bottom[i] = frequency;            reB = false;        }    }    success = reB;}int NumberTB::getFrequency(int num){    int count = 0;    for(int i = 0; i < len; i++)    {        if(bottom[i] == num)            count++;    }    return count;}int main(){    NumberTB nTB;    int* up = nTB.top;    for(int j = 0; j< len; j++) // 打印上排数组        cout<<*up++<<" ";     cout<<endl;    int* result = nTB.getBottom();    for(int i = 0; i < len; i++) // 打印下排数组        cout<<*result++<<" ";     cout<<endl;    cout<<"Run round: "<<nTB.round<<endl;     getchar();    return 0;}
结果


原创粉丝点击