我尝试打乱两个返回类型为整数的数组。例如,我有 {1, 2, 3} 和 {0, 5}。我得到的结果是{1,0}。所以,我不确定如何打印数组中的其余数字。
这是我所拥有的:
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}
如果您期望结果为:{1, 0, 2, 5, 3}
,我会这样写:
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;
}
关于java - 交错两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25733806/