給定兩個整型數組,本題要求找出不是兩者共有的元素。
輸入格式:
輸入分別在兩行中給出兩個整型數組,每行先給出正整數N(≤),隨后是N個整數,其間以空格分隔。
輸出格式:
在一行中按照數字給出的順序輸出不是兩數組共有的元素,數字間以空格分隔,但行末不得有多余的空格。題目保證至少存在一個這樣的數字。同一數字不重復輸出。
輸入樣例:
10 3 -5 2 8 0 3 5 -15 9 100
11 6 4 8 2 6 -5 9 0 100 8 1
輸出樣例:
3 5 -15 6 4 1
1 #include <stdio.h>
2 int main()
3 { 4 int one[30] = { 0 }; 5 int two[30] = { 0 }; 6 int three[30] = { 12 }; 7 int N,M,i,j,h,k=0; 8 scanf("%d", &N); 9 for (i = 0; i < N; i++) { 10 scanf("%d", &one[i]); 11 } 12 scanf("%d", &M); 13 for (j = 0; j < M; j++) { 14 scanf("%d", &two[j]); 15 } 16 int cnt = 0; 17 for (i = 0; i < N; i++) { 18 cnt = 0; 19 for (j = 0; j < M; j++) { 20 if (one[i] == two[j]) { 21 cnt = 1; 22 break; 23 } 24 } 25 if (cnt == 0) { 26 for (h = 0; h < k+1; h++) { 27 if (three[h] == one[i]&&three[h]!=0) { 28 cnt = 1; 29 } 30 } 31 if (cnt == 0) { 32 three[k] = one[i]; 33 k++; 34 } 35 } 36 } 37 for (j = 0; j < M; j++) { 38 cnt = 0; 39 for (i = 0; i < N; i++) { 40 if (two[j] == one[i]) { 41 cnt = 1; 42 break; 43 } 44 } 45 if (cnt == 0) { 46 for (h = 0; h < k + 1; h++) { 47 if (three[h] == two[j]&&three[h] != 0) { 48 cnt = 1; 49 } 50 } 51 if (cnt == 0) { 52 three[k] = two[j]; 53 k++; 54 } 55 } 56 } 57 for (h = 0; h < k - 1; h++) { 58 printf("%d ", three[h]); 59 } 60 printf("%d", three[h]); 61 return 0; 62 63 }
第一次忽略了輸出的數有0的情況,其與數組初始化為0沖突,改進了這行代碼后能解決當three[h]等於零時造成的錯誤答案。