//輸入測試後,答案不正確 //Java超級新手,求大神們幫幫忙QQ
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++];
}
}
讀資料的地方錯誤
第12列搬去第15列即可,如下
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++];
}
}
}
謝謝您的回答>< 但輸入後的答案仍然怪怪的Q_Q
你先確認你讀出來的資料正不正確,
先搞清楚問題出在哪裡,
是讀進來不正確?
還是分析的方法錯誤?
第33列寫錯了, 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++];
}
}
}