我制作了这个方法(interleave),它将3个数组作为输入,然后返回一个数组,该数组按顺序包含每个数组的元素。如果数组中没有元素,那么" - "添加到最后一个数组。
示例:如果这些数组被输入方法 - [" 1&#34 ;;" 2&#34 ;;" 3"],[" 4&# 34;],[" 5&#34 ;;" 6"]然后它将返回此数组 -
[" 1&#34 ;; " 4&#34 ;; " 5&#34 ;; " 2&#34 ;; " - &#34 ;; " 6&#34 ;; " 3&#34 ;; " - &#34 ;; " - "]
但是,当我打电话给我时,我没有得到任何结果。
static String[] interleave(String[] xs, String[] ys, String[] zs) {
int length1 = xs.length;
int length2 = ys.length;
int length3 = zs.length;
int larLength = 0;
if (((length1 > length2) && (length2 > length3) || ((length1 > length3) && (length3 > length2)))) {
larLength = length1;
}
else if (((length2 > length1) && (length1 > length3) || ((length1 > length3) && (length3 > length2)))) {
larLength = length2;
}
else if ((length3 > length2) && (length2 > length1)) {
larLength = length3;
}
String[] result = new String[larLength*larLength];
for(int i = 0; i < (larLength*larLength - 1); i++) {
if (xs[i] != null) {result[i] = xs[i];}
else {result[i] = "-";}
if (ys[i] != null) {result[i+1] = ys[i];}
else {result[i+1] = "-";}
if (zs[i] != null) {result[i+2] = zs[i];}
else {result[i+2] = "-";}
}
return result;
}
答案 0 :(得分:1)
您可以使用简单的Math.max(length1,length2,length3)
这里你真正需要的是数组* larLength
String[] result = new String[3*larLength];
最后,您需要修复在结果数组中添加元素的位置。它不是i
,i+1
和i+2
。
相反,正确的立场是:
第一个职位:resultIndex = i*3
,
第二个位置:resultIndex+1
第三位:resultIndex+2
所以你的代码看起来像这样:
String[] result = new String[3*larLength];
for(int i = 0; i < (larLength - 1); i++) {
int resultIndex = i*3;
if (xs[i] != null) {result[resultIndex] = xs[i];}
else {result[i] = "-";}
if (ys[i] != null) {result[resultIndex+1] = ys[i];}
else {result[i+1] = "-";}
if (zs[i] != null) {result[resultIndex+2] = zs[i];}
else {result[i+2] = "-";}
}
答案 1 :(得分:0)
public class Dummy {
public static void main(String[] args) {
String xs[] = {"1", "2", "3"}, ys[] = {"4"} , zs[] = {"5", "6"};
int larLength = Math.max(Math.max(xs.length, ys.length),
Math.max(ys.length, zs.length));
int ind = 0;
String res[] = new String[3*larLength];
for (int i=0;i<larLength;i++) {
if (i<xs.length) res[ind++] = xs[i];
else res[ind++] = "-";
if (i<ys.length) res[ind++] = ys[i];
else res[ind++] = "-";
if (i<zs.length) res[ind++] = zs[i];
else res[ind++] = "-";
}
for (int i=0;i<res.length;i++) {
System.out.print(res[i]);
}
}