合并两个数组,例如,两个数组的元素相互交替定位

我有两个数组,我喜欢以某种方式合并,所以我的输出应该是这样的


我们也可以选择多维数组吗?


public class MeregTwoArray {


public static int[] mergeArray(int[] a, int[] b) {

    int length = (a.length + b.length);

    int result[] = new int[length];

    for (int i = 0; i <= a.length-1;) {

        result[i] = a[i];

        for (int j = 0; j <= b.length-1;) {

            result[i + 1] = b[j];

            j++;

            break;

        }

        i++;

    }

    return result;

}


public static void main(String[] args) {

    int a[] = {1, 3, 5, 6, 7, 8};

    int b[] = {4, 2, 7, 6, 4, 2};

    int result[] = mergeArray(a, b);


    for (int i = 0; i <= result.length - 1; i++) {

        System.out.println(result[i]);

    }

}


}

电流输出:1 3 5 6 7 8 4 0 0 0 0 0


预期输出:


1 4 3 2 5 7 6 6 7 4 8 2


炎炎设计
浏览 88回答 2
2回答

慕虎7371278

这有帮助吗?public static int[] mergeArray(int[] a, int[] b) {&nbsp; &nbsp;int result[] = new int[a.length + b.length];&nbsp; &nbsp;int targetIdx = 0;&nbsp; // result arrray index counter&nbsp; &nbsp;int i, j;&nbsp;&nbsp; &nbsp;for(i = 0, j = 0; i <= a.length-1; ) {&nbsp; &nbsp; &nbsp; result[targetIdx] = a[i++]; // put element from first array&nbsp;&nbsp; &nbsp; &nbsp; if(j < b.length) { // if second array element is there&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result[++targetIdx] = b[j++]; // put element from second array&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;targetIdx++;&nbsp; }&nbsp; // If b.length > a.length&nbsp; while(j < b.length) {&nbsp; &nbsp; &nbsp; result[taargetIdx++] = b[j++];&nbsp; }&nbsp; return result;}

陪伴而非守候

您可以维护 2 个索引,一个用于“合并”数组,一个用于循环迭代的索引。因为您正在合并,所以您需要在每次迭代中将目标索引增加 2:public static int[] mergeArray(int[] a, int[] b) {&nbsp; &nbsp; int length = (a.length + b.length);&nbsp; &nbsp; int result[] = new int[length];&nbsp; &nbsp; for (int i = 0, e = 0; i <= a.length - 1; i++, e += 2) {&nbsp; &nbsp; &nbsp; &nbsp; result[e] = a[i];&nbsp; &nbsp; &nbsp; &nbsp; result[e + 1] = b[i];&nbsp; &nbsp; }&nbsp; &nbsp; return result;}输出预期的1 4 3 2 5 7 6 6 7 4 8 2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java