Java: Interleaving multiple arrays into a single array

后端 未结 5 583
误落风尘
误落风尘 2020-12-19 06:13

I found similar question about interleaving two arraylists into one, but its in PHP. I was asked this question in interview as well but could\'nt solve it, came back to SO t

5条回答
  •  Happy的楠姐
    2020-12-19 06:37

    I believe the mod (%) operations in Matt's answer are incorrect. Under the same assumption (that the arrays are the same length), I'd propose the following solution instead:

    static int[] merge(final int[] a, final int[] b)
    {
        final int[] result = new int[a.length * 2];
    
        for (int i=0; i < a.length; i++)
        {
            result[i << 1] = a[i];
            result[(i << 1) + 1] = b[i];
        }
    
        return result;
    }
    

    I tested (very briefly), and it appears to work, but of course makes no attempt to handle error conditions such as null arguments or input arrays mismatched in size.

提交回复
热议问题