2 回答
TA贡献1802条经验 获得超4个赞
这有帮助吗?
public static int[] mergeArray(int[] a, int[] b) {
int result[] = new int[a.length + b.length];
int targetIdx = 0; // result arrray index counter
int i, j;
for(i = 0, j = 0; i <= a.length-1; ) {
result[targetIdx] = a[i++]; // put element from first array
if(j < b.length) { // if second array element is there
result[++targetIdx] = b[j++]; // put element from second array
}
targetIdx++;
}
// If b.length > a.length
while(j < b.length) {
result[taargetIdx++] = b[j++];
}
return result;
}
TA贡献1757条经验 获得超8个赞
您可以维护 2 个索引,一个用于“合并”数组,一个用于循环迭代的索引。因为您正在合并,所以您需要在每次迭代中将目标索引增加 2:
public static int[] mergeArray(int[] a, int[] b) {
int length = (a.length + b.length);
int result[] = new int[length];
for (int i = 0, e = 0; i <= a.length - 1; i++, e += 2) {
result[e] = a[i];
result[e + 1] = b[i];
}
return result;
}
输出预期的1 4 3 2 5 7 6 6 7 4 8 2
添加回答
举报