Java:将多个数组交织成一个数组 [英] Java: Interleaving multiple arrays into a single array

查看:33
本文介绍了Java:将多个数组交织成一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了类似关于将两个数组列表交织成一个的问题,但它在 PHP 中.我在面试中也被问到这个问题但无法解决,回到 SO 看看它是否已经解决了,但我只能找到这个 论文

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 to look if it was addressed already, but i could only find this paper

那么任何指向伪代码或方法定义的指针?

So any pointers to pseudo code or method definition ?

Big(O) 限制:O(n) - 时间成本和 O(1) - 空间成本

Big(O) restrictions : O(n) - time cost and O(1) - space cost

示例:
a[]= a1, a2, ..., an
b[]= b1, b2, ..., bn
将arraylist重新排列为a1, b1, a2, b2, ..., an, bn

Example:
a[]= a1, a2, ..., an
b[]= b1, b2, ..., bn
Rearrange the arraylist to a1, b1, a2, b2, ..., an, bn

Editv1.0 : Arraylists a[] 和 b[] 大小相同

Editv1.0 : Arraylists a[] and b[] are of same size

Editv2.0 :如果问题扩展为在给定的两个数组之一中重新排列,但不创建新数组怎么办?

Editv2.0 : What if the question is extended to rearrange in one of given two arrays, but not create a new array ?

推荐答案

为简单起见,假设数组长度相同,并且是 int 数组.

For simplicity, assume that the arrays are the same length, and are int arrays.

int[] merge(int[] a, int[] b)
{
    assert (a.length == b.length);

    int[] result = new int[a.length + b.length];

    for (int i=0; i<a.length; i++)
    {
        result[i*2] = a[i];
        result[i*2+1] = b[i];
    }

    return result;
}

这篇关于Java:将多个数组交织成一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆