Java 合并两个数组,例如,两个数组的元素彼此交替放置

Java 合并两个数组,例如,两个数组的元素彼此交替放置,java,Java,我有两个数组,我喜欢以某种方式合并,所以我的输出应该是这样的 我们也可以用多维数组吗 public class MeregTwoArray { public static int[] mergeArray(int[] a, int[] b) { int length = (a.length + b.length); int result[] = new int[length]; for (int i = 0; i <= a.length-1;) {

我有两个数组,我喜欢以某种方式合并,所以我的输出应该是这样的

我们也可以用多维数组吗

public class MeregTwoArray {

public static int[] mergeArray(int[] a, int[] b) {
    int length = (a.length + b.length);
    int result[] = new int[length];
    for (int i = 0; i <= a.length-1;) {
        result[i] = a[i];
        for (int j = 0; j <= b.length-1;) {
            result[i + 1] = b[j];
            j++;
            break;
        }
        i++;
    }
    return result;
}

public static void main(String[] args) {
    int a[] = {1, 3, 5, 6, 7, 8};
    int b[] = {4, 2, 7, 6, 4, 2};
    int result[] = mergeArray(a, b);

    for (int i = 0; i <= result.length - 1; i++) {
        System.out.println(result[i]);
    }
}

}
电流输出: 1. 3. 5. 6. 7. 8. 4. 0 0 0 0 0

预期产出:

一, 4. 3. 2. 5. 7. 6. 6. 7. 4. 8. 这有帮助吗

public static int[] mergeArray(int[] a, int[] b) {
   int result[] = new int[a.length + b.length];
   int targetIdx = 0;  // result arrray index counter
   int i, j; 


   for(i = 0, j = 0; i <= a.length-1; ) {
      result[targetIdx] = a[i++]; // put element from first array 
      if(j < b.length) { // if second array element is there
         result[++targetIdx] = b[j++]; // put element from second array
      }
     targetIdx++;
  }

  // If b.length > a.length
  while(j < b.length) {
      result[taargetIdx++] = b[j++];
  }
  return result;
}

您可以维护两个索引,一个用于合并数组,另一个用于循环迭代。因为要合并,所以在每次迭代中需要将目标索引增加2:

public static int[] mergeArray(int[] a, int[] b) {
    int length = (a.length + b.length);
    int result[] = new int[length];

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

    return result;
}

它输出预期的1 4 3 2 5 7 6 7 4 8 2

当您在其他数组中有更多项时,此中断。@SamzSakerz我看不出有此要求。这可以很容易地处理1或2个条件