---
title: "腾讯算法面试题算法与代码"
author: "yydcj"
date: "2010-10-22T11:22:49Z"
tags: ["算法", "腾讯", "面试"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-10-22T11:22:49Z"
id: 791322
url: "https://yydcj.iteye.com/blog/791322"
---

题目是这样的：给你10分钟时间，根据上排给出十个数，在其下排填出对应的十个数

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

　　上排的十个数如下：

　　【0，1，2，3，4，5，6，7，8，9】  
代码如下：

/\** \*/  
/\**  
 * http://yydcj.iteye.com/  
 \*/  
public class Test {  
    public static void main(String\[] args) {  
        NumberTB nTB = new NumberTB(18);  
        int\[] result = nTB.getBottom();  
        for (int i = 0; i &lt; result.length; i++) {  
            System.out.print(result\[i] + " ");  
        }  
    }

    static class NumberTB {

        private int\[] top;  
        private int\[] bottom;  
        private int len;  
        private boolean success;

        // please into len &gt;= 4　　  
        public NumberTB(int len) {  
            this.len = len &lt;= 4 ? 4 : len;  
            this.success = false;  
            this.top = new int\[this.len];  
            this.bottom = new int\[this.len];

            // format top　　  
            for (int i = 0; i &lt; this.len; i++) {  
                this.top\[i] = i;  
            }  
        }

        public int\[] getBottom() {  
            int i = 0;  
            while (!this.success) {  
                i++;  
                setNextBottom();  
            }  
            System.out.println("执行了: " + i + "次循环得到结果");  
            return this.bottom;  
        }

        // set next bottom　　  
        private void setNextBottom() {  
            boolean reB = true;  
            for (int i = 0; i &lt; this.len; i++) {  
                int frequecy = getFrequecy(i);  
                if (this.bottom\[i] != frequecy) {  
                    this.bottom\[i] = frequecy;  
                    reB = false;  
                }  
            }  
            this.success = reB;  
        }

        // get frequency in bottom　　

        private int getFrequecy(int num) {  
            int count = 0;  
            for (int i = 0; i &lt; this.len; i++) {  
                if (this.bottom\[i] == num)  
                    count++;  
            }  
            return count;  
        }  
    }  
}

下面给出一个更具一般性的结论：

　　这个是有规律可循的，不仅0~9有唯一解，0~n都只有唯一解。关键是最后面一个1它可以左右移动，1和2下面的数永远是2和1，0下面对应的数为n-3（n&gt;=3），上排数n-3下面对应的数为1，其它上排数下面对应为0就ok了。有了这个一般性的结论再大的数都可以马上给出答案。

　　比如 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

　　 12 2 1 0 0 0 0 0 0 0 0 0 1 0 0 0

　　请大家验证，这个算法可以用到数据压缩领域。