用交替值连接两个数组 [英] Concatenating two arrays with alternating values

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

问题描述

用交替值连接两个数组的最佳方法是什么?

What is the best way to concatenate two arrays with alternating values?

让我们说 array1 是:

[1, 3, 5, 7]

array2 是:

[2, 4, 6, 8]

我想结合这两个数组,所以结果是:

I want to combine these two arrays, so that the result is:

[1, 2, 3, 4, 5, 6, 7, 8]

在Java中:

int[] a1 = { 1, 3, 5, 7 };
int[] a2 = { 2, 4, 6, 8 };
int[] concat = new int[a1.length * 2];
for (int i = 0; i < concat.length; i++) {
    // concatenation
}
System.out.println(concat.toString());
// should be [1, 2, 3, 4, 5, 6, 7, 8]

更新:不需要排序,因为已经使用 Arrays.sort(array)

Update: No sorting is required, as the arrays are already sorted, using Arrays.sort(array)

推荐答案

基本方法

int[] concat = new int[a1.length * 2];
int index = 0;
for (int i = 0; i < a1.length; i++) {
    concat[index++] = a1[i];
    concat[index++] = a2[i];
}

假设两个数组的大小相同.

assuming that both array will be of same size.

这篇关于用交替值连接两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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