1、两个有序int数组,合并成一个?
答:用两个下标移动,判断大小,写入到一个新的数组里面
public static int[] add(int[] l1, int[] l2) {
if (l1 == null || l1.length == 0) return l2;
if (l2 == null || l2.length == 0) return l1;
int[] l3 = new int[l1.length + l2.length];
int l1Index = 0;
int l2Index = 0;
for (int i = 0; i < l1.length + l2.length; i++) {
if (l1Index == l1.length ) {
for (int j = l2Index; j < l2.length; j++) {
l3[i + j - l2Index] = l2[j];
}
break;
}
if (l2Index == l2.length ) {
for (int j = l1Index; j < l1.length; j++) {
l3[i + j - l1Index] = l1[j];
}
break;
}
if(l1[l1Index] < l2[l2Index]) {
l3[i] = l1[l1Index];
l1Index ++;
} else {
l3[i] = l2[l2Index];
l2Index ++;
}
}
return l3;
}
2、求一个数的n次方?
答:我写的是递归,显然不是面试官想要的答案。说时间复杂度能不能降一下,不会啦!
public static long pow(long x, int n) {
if (n == 0) {
return 1L;
}
return x * pow(x, n - 1);
}
网上百度啦一个答案,没怎么看懂,放出来大家瞅一瞅
static long power(long a, int n) {
long r = 1;
int t = 0;
while (n >= 1) {
if ((n & 1) == 1) {
r *= a;
}
a *= a;
n = n >> 1;
}
return r;
}
#腾讯笔试##大数据求职#