2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
這有幫助嗎?
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貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以維護(hù) 2 個(gè)索引,一個(gè)用于“合并”數(shù)組,一個(gè)用于循環(huán)迭代的索引。因?yàn)槟诤喜?,所以您需要在每次迭代中將目?biāo)索引增加 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;
}
輸出預(yù)期的1 4 3 2 5 7 6 6 7 4 8 2
添加回答
舉報(bào)