腾讯算法面试题解答

才在JavaEye论坛看一个帖子求助腾讯一道面试题的解法。

题目是这样的:给你10分钟时间,根据上排给出十个数,在其下排填出对应的十个数
要求下排每个数都是先前上排对应那个数在下排十个数中出现的次数。
上排的十个数如下:
【0,1,2,3,4,5,6,7,8,9】

 

JavaEye论坛里面有人给出了一个java实现的算法。

public class Test
{
  public static void main(String[] args)
  {
    NumberTB nTB = new NumberTB(10);
    
    int[] result = nTB.getBottom();
    for(int i=0;i<result.length;i++)
    {
      System.out.print(result[i] + " ");
    }
  }
}

class NumberTB
{
  private int[] top;
  private int[] bottom;
  private int len;
  private boolean success;
  
  //please into len >= 4
  public NumberTB(int len)
  {
    this.len = len <= 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<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<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<this.len;i++)
    {
      if(this.bottom[i] == num)
        count++;
    }
    
    return count;
  }
}

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

这个是有规律可循的,不仅0~9有唯一解,0~n都只有唯一解。关键是最后面一个1它可以左右移动,1和2下面的数永远是2和1,0下面对应的数为n-3(n>=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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值