【校招笔试】【2016】【乐视】跳跃的蚂蚱
题目描述:

个人思路如下:(欢迎大家讨论)
1.每次正向或反向,是两种情况,自然想到可以用二叉树来保存每次的结果
2.想要数据结构简单些,通过观察,可知该结果是一个完全二叉树的结构,于是想到用堆的表示方法,用一个数组来表示该二叉树
如图:(有点丑,见谅)

则树的深度h就是每步的大小,节点数字就代表当前的坐标
代码如下:
1 import java.util.Scanner; 2 public class Le_2 { 3 public static void main(String[] args){ 4 Scanner scan = new Scanner(System.in); 5 int x; 6 int max = 100000; 7 while(scan.hasNext()){ 8 x = scan.nextInt(); 9 int[] t = new int[max]; 10 t[1] = 0; 11 int sum = 0; 12 int step = 1; 13 int h = 0; 14 for(int i = 1; i < max/2; ++i){ 15 // 当前高度 16 if(i == (int)Math.pow(2, h)){ 17 h++; 18 } 19 // 左子树做减法 20 t[2*i] = (t[i] - h); 21 //System.out.printf("t[%d] = %d\n", 2*i,t[2*i]); 22 if (x == t[2*i]){ 23 step = h; 24 break; 25 } 26 // 右子树做加法 27 t[2*i + 1] = (t[i] + h); 28 //System.out.printf("t[%d] = %d\n", 2*i+1,t[2*i+1]); 29 if (x == t[2*i + 1]){ 30 step = h; 31 break; 32 } 33 } 34 System.out.println(step); 35 } 36 } 37 }

浙公网安备 33010602011771号