交错两个数组 [英] Interleave two arrays

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

问题描述

我尝试使用返回类型整数对两个数组进行混洗.例如,我有{1、2、3}和{0、5}.我得到的结果是{1,0}.因此,我不确定如何将其余数字打印在数组中.

I try to shuffle two array with return type integer. For example, I have {1, 2, 3} and {0, 5}. The result I get was {1,0}. So, I'm not sure how would I print the rest of numbers in array.

这就是我所拥有的:

public int[] shuffle(int[] A, int[] B) {
    int shuff = 0;
    int[] out = { A[shuff], B[shuff] };

    for (int i = 0; i < A.length; i++) {
        for (int j = 0; j < B.length; j++) {
            int shuffle = A[i];
            A[i] = B[j];
            B[j] = shuffle;
        }
    }
    return out;
}

推荐答案

使用:

int[] out = { A[shuff], B[shuff] };

您只需要输入A的第一个数字和B的第一个数字,那么循环根本就没有关系.然后返回,因此它将始终返回 {1,0}

you are just putting first number of A and first number of B, your loop doesn't matter at all. Then you return out, so it's going to always return {1,0}

如果您期望结果为: {1、0、2、5、3} ,我会这样写:

If you expect result as: {1, 0, 2, 5, 3} I would write it this way:

public static int[] interleave(int[] a, int[] b) {
    int[] out = new int[a.length + b.length];
    int j = 0;
    int maxLength = Math.max(a.length, b.length);
    for (int i = 0; i < maxLength; i++) {
        if (i < a.length) {
            out[j++] = a[i];
        }
        if (i < b.length) {
            out[j++] = b[i];
        }
    }
    return out;
}

运行代码段: http://rextester.com/ISTE29382

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

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