您的位置:首页 > 职场人生

一道google的面试题(据说)

2018-01-10 17:29 351 查看
1. 原题(同事给的)

Max Howell 参加了谷歌的面试,出题人竟然要求 Max Howell 在白板上作出解答,Max Howell 当然愤怒地拒绝了,回家以后马上在微博上跟我们分享他的吐槽:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
看来在白板上作出反转二叉树的解答并不容易呢?那么在 ScriptOJ 有上 OJ 系统会不会更方便一些呢?

假如有这样一个二叉树,

4
/   \
3      2
/  \    / \
7     1  2   3
/ \   /
6   5 9
使用广度优先的原则用数组的表示就是 [4, 3, 2, 7, 1, 2, 3, 6, 5, 9, null, null, null, null, null],二叉树中的空位用 null 表示。

进行反转以后会变成

4
/   \
2      3
/  \    /  \
3     2  1     7
\   /  \
9 5    6
使用广度优先的原则用数组的表示就是 [4, 2, 3, 3, 2, 1, 7, null, null, null, null, null, 9, 5, 6]。

请实现函数 invertTree,它接受一个表示二叉树的数组,返回表示这个反转二叉树的数组。

请注意,提交后提示中显示的 1,2,3,,,4,5 表示的是 1, 2, 3, null, null, 4, 5。


2.1 code

package org.rocky.learn.algorithm;
/**
* Created by admin on 2018/1/10.
*/
public class ConvertArray {
public static Integer[] convertTree(Integer[] from){
int length = from.length;
int height = (int) Math.ceil(log(length, 2));
int should_size = (int) Math.pow(2, height)-1;
Integer[] result = new Integer[should_size];
result = copyArray(from, result);
int index = 0;
for(int i=0; i<height; i++){
int size = (int) Math.pow(2, i);
result = convertArray(result, index, size);
index += size;
}
return result;
}

public static Integer[] copyArray(Integer[] from, Integer[] to){
for(int i=0; i<Math.min(from.length, to.length); i++){
to[i] = from[i];
}
return to;
}

public static double log(double value, double base){
return Math.log(value)/Math.log(base);
}
public static Integer[] convertArray(Integer[] from, int beginIndex, int size){
int length = from.length;
Integer[] to = new Integer[length];
for (int i=0; i<length; i++){
if(i<beginIndex || i>beginIndex+size-1)
to[i] = from[i];
else
to[i] = from[beginIndex + size -1 -(i-beginIndex)];
}
return to;
}

public static void main(String[] args){
Integer[] to = convertTree(new Integer[]{1,2,3,4,5,6});
for(int i=0; i<to.length; i++){
System.out.print(to[i]==null?"":to[i]);
if(i<to.length-1)
System.out.print(",");
}
}
}


2.2 更新

public static Integer[] convertArray(Integer[] array, int beginIndex, int size){
int length = array.length;
if(beginIndex >=0 && beginIndex <= length-1){
int endIndex = beginIndex+size > length ? length : beginIndex + size;
for(int i=beginIndex; i<(endIndex+beginIndex)/2; i++){
int index = endIndex-1-(i-beginIndex);
Integer temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
return  array;
}


3. 总结

写出来的速度反应编程能力, fighting!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: