根据上排数填下排数 【微软面试100题 第六题】

题目要求:

  根据上排给出的十个数,在其下排填出对应的十个数。

  要求下排每个数都是先前上排那十个数在下排出现的次数。

  例如:上排: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次...以此类推

题目分析:

  先初始化下排的十个数都为0,然后根据上排逐渐更新下排的值,直到上排和下排数据匹配为止。

top0123456789 
bottom0000000000第一行
10000000000第二行
9000000001第三行
8100000010第四行
7210000100第五行
6210001000第六行
6210001000第七行

   分析上表:  bottom的第一排为初始化值,全部为0.

        bottom第二排的值是根据第一排的bottom和top得来的。top中的0在第一排中有10个,则更新第二排中对应top为0的那个数为10。同理top为1-9在第一排中没有,则更新第二排中对应top为1-9的那些数为0.

        ......

        bottom第六行的值根据top和bottom第五行的值来更新,在第五行中有6个0,则在第六行中top为0的那一列为6;在第五行中有2个1,则在第六行中top为1的那一列为2...

        bottom第七行的值根据top和bottom第六行的值来更新,在第六行中有6个0,则在第七行中top为0的那一列为6;在第六行中有2个1,则在第七行中top为1的那一列为2...第六行和第七行数据相同,则更新完成。

代码:

#include <iostream>

using namespace std;

const int len = 10;
class NumberTb
{
private:
    int top[10];
    int bottom[10];
    bool success;
public:
    NumberTb();
    ~NumberTb(){}
    int *getBottom();
    void setNextBottom();
    int getFrequency(int num);
};
NumberTb::NumberTb()
{
    success = false;
    for(int i = 0;i<len;i++)
    {
        top[i] = i;
        bottom[i] = 0;
    }
}
int *NumberTb::getBottom()
{
    while(!success)
        setNextBottom();
    return bottom;
}
void NumberTb::setNextBottom()
{
    bool reb = true;
    for(int i=0;i<len;i++)
    {
        int fre = getFrequency(i);
        if(bottom[i]!=fre)
        {
            bottom[i] = fre;
            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(void)
{
    NumberTb nTb;
    int *result = nTb.getBottom();

    cout << "top:   ";
    for(int i = 0;i<len;i++)
        cout << i << " ";
    cout << endl;
    cout << "bottom:";
    for(int i=0;i<len;i++)
        cout << *(result+i) << " ";
    cout << endl;

    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/tractorman/p/4053794.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值