7

我正在为我的“问题”寻找解决方案,这不是一个丑陋的黑客。

在我的 Java 代码中,我有两个数组,两个数组的长度都未知(因此它们的长度可能不同)。我想像这样对它们进行排序:

Array A: {1, 2, 3, 4, 5}
Array B: {6, 7, 8}

New Array: {1, 6, 2, 7, 3, 8, 4, 5}

有没有很好的方法来实现这一点?

谢谢

4

2 回答 2

7
int[] res = new int[a.length + b.length];
int p = 0;
int last = Math.max(a.length, b.length);
for (int i = 0 ; i != last ; i++) {
    if (i < a.length) res[p++] = a[i];
    if (i < b.length) res[p++] = b[i];
}
于 2012-12-19T12:08:58.650 回答
2

If it is likely that there are many more in one array than the other, it should be faster to zip the first part and then bulk copy the rest using System.arrayCopy. It also simplifies dasblinkenlight's for loop by removing the ifs.

int[] res = new int[a.length + b.length];
int p = 0;
//zip what we can
int last = Math.min(a.length, b.length);    
for (int i = 0; i != last; i++) {
    res[p++] = a[i];
    res[p++] = b[i];
}
//now add the remaining
int aRemain = a.length - last;
if(aRemain > 0) {
  System.arrayCopy(a, last, res, p, aRemain);
}
else
{
  int bRemain = b.length - last;
  if(bRemain > 0) {
    System.arrayCopy(b, last, res, p, bRemain);
  }
}
于 2012-12-19T12:32:29.923 回答