0

## 陣列合併問題

//輸入測試後，答案不正確 //Java超級新手，求大神們幫幫忙ＱＱ
input:
3
1 2 3
3
4 5 6
output:
2 4 3 3

package HW1;

import java.util.Scanner;

public class HW3 {

``````public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int[] a = new int[10];
int[] b = new int[10];
int[] c = new int[20];
int aSize = input.nextInt();
int bSize = input.nextInt();
for (int i = 0; i < aSize; i++) {
a[i] = input.nextInt();
}
for (int j = 0; j < bSize; j++) {
b[j] = input.nextInt();
}

merge(a, b, c, aSize, bSize);

for (int k = 0; k < aSize + bSize; k++) {
System.out.print(c[k] + " ");
}
}

public static void merge(int[] a, int[] b, int[] c, int aSize, int bSize) {
int i = 0;
int j = 0;
int k = 0;

while ((i < aSize) && (j < bSize)) {

if (a[i] < b[i]) {
c[k++] = a[i++];

}

else {
c[k++] = b[j++];

}
}

while (i < aSize) {
c[k++] = a[i++];
}

while (j < bSize) {
c[k++] = b[j++];
}

}
``````

### 1 個回答

1

iT邦超人 1 級 ‧ 2019-04-09 12:01:47

``````import java.util.Scanner;

public class HW3 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int[] a = new int[10];
int[] b = new int[10];
int[] c = new int[20];
int aSize = input.nextInt();
for (int i = 0; i < aSize; i++) {
a[i] = input.nextInt();
}
int bSize = input.nextInt();
for (int j = 0; j < bSize; j++) {
b[j] = input.nextInt();
}

merge(a, b, c, aSize, bSize);

for (int k = 0; k < aSize + bSize; k++) {
System.out.print(c[k] + " ");
}
}

public static void merge(int[] a, int[] b, int[] c, int aSize, int bSize) {
int i = 0;
int j = 0;
int k = 0;

while ((i < aSize) && (j < bSize)) {
if (a[i] < b[i]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < aSize) {
c[k++] = a[i++];
}
while (j < bSize) {
c[k++] = b[j++];
}
}
}
``````
LuluLee iT邦新手 5 級 ‧ 2019-04-09 13:50:12 檢舉

`if (a[i] < b[i]) {`

`if (a[i] < b[j]) {`才對

``````import java.util.Scanner;

public class HW3 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int[] a = new int[10];
int[] b = new int[10];
int[] c = new int[20];
int aSize = input.nextInt();
for (int i = 0; i < aSize; i++) {
a[i] = input.nextInt();
}
int bSize = input.nextInt();
for (int j = 0; j < bSize; j++) {
b[j] = input.nextInt();
}

merge(a, b, c, aSize, bSize);

for (int k = 0; k < aSize + bSize; k++) {
System.out.print(c[k] + " ");
}
}

public static void merge(int[] a, int[] b, int[] c, int aSize, int bSize) {
int i = 0;
int j = 0;
int k = 0;

while ((i < aSize) && (j < bSize)) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < aSize) {
c[k++] = a[i++];
}
while (j < bSize) {
c[k++] = b[j++];
}
}
}
``````