zoukankan      html  css  js  c++  java
  • 根据上排数填下排数 【微软面试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,然后根据上排逐渐更新下排的值,直到上排和下排数据匹配为止。

    top 0 1 2 3 4 5 6 7 8 9  
    bottom 0 0 0 0 0 0 0 0 0 0 第一行
    10 0 0 0 0 0 0 0 0 0 第二行
    9 0 0 0 0 0 0 0 0 1 第三行
    8 1 0 0 0 0 0 0 1 0 第四行
    7 2 1 0 0 0 0 1 0 0 第五行
    6 2 1 0 0 0 1 0 0 0 第六行
    6 2 1 0 0 0 1 0 0 0 第七行

       分析上表:  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
  • 相关阅读:
    Liferay7 BPM门户开发之1:Liferay7开发环境准备
    Liferay-Activiti 企业特性功能介绍 (新版Liferay7)
    Liferay-Activiti 功能介绍 (新版Liferay7基本特性)
    Java入门开发POI读取导入Excel文件
    JAVA动态代理和方法拦截(使用CGLib实现AOP、方法拦截、委托)
    JFrame、JPanel 、Layout开发的简单例子
    Smart/400开发上手5: Cobol开发标准
    Smart/400开发上手4: 调试Cobol代码 (DEBUG with QBATCH)
    Netbeans Platform 工程,免安装JDK
    网络延迟测试结果
  • 原文地址:https://www.cnblogs.com/tractorman/p/4053794.html
Copyright © 2011-2022 走看看