Java的:交错多个阵列成一个阵列 [英] Java: Interleaving multiple arrays into a single array
问题描述
我发现<一个href=\"http://stackoverflow.com/questions/1860490/interleaving-multiple-arrays-into-a-single-array\">similar约两的ArrayList交织成一个问题,但其在PHP。有人问我,在这个问题采访很好,但could'nt解决它,回来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
因此,任何指向伪code或方法的定义?
So any pointers to pseudo code or method definition ?
大(O)限制:为O(n) - 时间成本和O(1) - 空间成本
Big(O) restrictions : O(n) - time cost and O(1) - space cost
示例:结果
一个[] = A1,A2,...,一个搜索
B〔] = B1,B2,......,BN结果
重新排列数组列表为A1,B1,A2,B2,...,一,BN
Example:
a[]= a1, a2, ..., an
b[]= b1, b2, ..., bn
Rearrange the arraylist to a1, b1, a2, b2, ..., an, bn
Editv1.0 :一个的ArrayList []和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屋!