猿问

如何在 1 个循环中合并 2 个数组?

我被告知要做


void mergeArrays(int[] ar1 , int[] ar2)

对于这样的输入:


int[] ar1 = {1,2,3,4}

int[] ar2 = {5,6,7,8}

这是我的代码:


 public static void mergeArray(int[] ar1 , int[] ar2)    {

        int[] res = new int[ar1.length+ar2.length];

        int counter = 0;

        for(int a = 0; a<ar1.length; a++)

        {

            res[a] = ar1[a];

            counter++;

        }

        for(int b = 0; b<ar2.length; b++)

        {

            res[counter++] = ar2[b];

        }

        for(int temp = 0; temp<res.length;temp++)

        {

            System.out.print(res[temp]+" ");

        }

输出12345678。


这是使用 2 个循环完成的。现在,我如何使用单个循环来做到这一点?


GCT1015
浏览 188回答 2
2回答

12345678_0001

是的,你可以在一个循环中完成,&nbsp; &nbsp; &nbsp; &nbsp; int len = arr1.length + arr2.length;&nbsp; &nbsp; &nbsp; &nbsp; int[] res = new int[len];&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0, j=0; i<len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i<arr1.length){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res[i] = arr1[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res[i] = arr2[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }当两个数组的长度不同时,这也将起作用。

翻过高山走不出你

不同长度的数组&nbsp; &nbsp; int[] result = new int[ar1.length + ar2.length];&nbsp; &nbsp; for(int i = 0; i < result.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = i < ar1.length ? ar1[i] : ar2[i - ar1.length]; // comparison&nbsp; &nbsp; }等长数组&nbsp; &nbsp; int[] result = new int[ar1.length + ar2.length];&nbsp; &nbsp; for(int i = 0; i < ar1.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = ar1[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // no&nbsp; &nbsp; &nbsp; &nbsp; result[ar1.length + i] = ar2[i]; // comparison&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }在此处查看(并执行)完整实现。
随时随地看视频慕课网APP

相关分类

Java
我要回答