我想组合两个排序的数组,因此只需要进行比较和打印。我遇到的问题是,输出是错误的,因为程序只是通过第二个for循环。我需要做些什么来使其发挥作用?
result = {1,2,3,3,3,5,5,6,7,8,9,9,10}
public static void main(String[] args) {
int[] array1 = { 1, 3, 3, 5, 6, 9 };
int[] array2 = { 2, 3, 5, 7, 8, 9, 10 };
int i;
int j;
int a;
int b;
for (j = 0; j < array1.length; j++) {
a = array1[j];
for (i = 0; i < array2.length; i++) {
b = array2[i];
if (a < b) {
System.out.print(a);
} else if (b < a) {
System.out.print(b);
} else if (a == b) {
System.out.print(a + b);
}
}
}
}
}
答案 0 :(得分:0)
algo -
int i=0, j=0, k=0
int[] result = new int[arr1.length+arr2.length];
while (i<arr1.length && j<arr2.length) {
if(arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
// or if u just want to print do a sysout.
} else {
result[k++] = arr2[j++];
}
}
while(i<arr1.length)
result[k++] = arr1[i++];
while(j<arr2.length)
result[k++] = arr2[j++];