Java: Interleaving multiple arrays into a single array

后端 未结 5 586
误落风尘
误落风尘 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条回答
  •  遥遥无期
    2020-12-19 06:49

    I've done up a small solution going on the assumption that you are talking about using the ArrayList (see my comment on the question). I may be oversimplifying the problem based on some of the responses here, but here goes anyway.

    The below example takes a and b both of type ArrayList and interleaves them by inserting b[0] after a[0], b[1] after a[1] etc. This snippet of course naively assumes that a and b are of the same size as per your Edit v1.0. It also does not create a new ArrayList as per your Edit v2.0.

    //a and b are of type ArrayList
    for (int i = a.size(); i > 0; i--)
    {
        a.add(i, b.get(i - 1));
    }
    

    No matter what happens if you are combining the ArrayLists you're going to have twice the size.

提交回复
热议问题