练习7-4 找出不是两个数组共有的元素
1 #include<stdio.h> 2 4 int array_in(int x, int a[], int n); 5 6 int main(void) 7 { 8 int m, n, k; //三个数组的大小 9 10 /*第一个数组,数组长度是变量,C99支持,但vs不支持*/ 11 scanf("%d", &m); 12 int a[m]; 13 for (int i = 0; i < m; i++) 14 { 15 scanf("%d", &a[i]); 16 } 17 18 /*第二个数组*/ 19 scanf("%d", &n); 20 int b[n]; 21 for (int i = 0; i < n; i++) 22 { 23 scanf("%d", &b[i]); 24 } 25 26 /*第三个数组,有可能两个数组中的元素都不相同*/ 27 int c[m + n]; 28 29 int count = 0; //两个数组中不相同元素的个数 30 31 /*查找到不相同的元素,放到第三个数组中*/ 32 for (int i = 0; i < m; i++) 33 { 34 if (array_in(a[i], b, n) == 0 && array_in(a[i], c, count) == 0) //避免第一个数组中有多个相同的元素在第二数组中不存在的情况 35 { 36 c[count] = a[i]; 37 count++; 38 } 39 } 40 for (int i = 0; i < n; i++) 41 { 42 if (array_in(b[i], a, m) == 0 && array_in(b[i], c, count) == 0) 43 { 44 c[count] = b[i]; 45 count++; 46 } 47 } 48 49 for(int i = 0; i < count; i++) 50 { 51 if (i == 0) 52 { 53 printf("%d", c[i]); 54 } 55 else 56 { 57 printf(" %d", c[i]); 58 } 59 } 60 61 return 0; 62 } 63 64 /* 65 判断x是否在数组a中; 66 如果在,返回1;不在,返回0; 67 n是查找数组a中元素的长度; 68 */ 69 int array_in(int x, int a[], int n) 70 { 71 int ret = 0; 72 73 for (int i = 0; i < n; i++) 74 { 75 if (x == a[i]) 76 { 77 ret = 1; 78 break; 79 } 80 } 81 82 return ret; 83 }
解法二
1 #include <stdio.h> 2 #define MAXN 20 3 //去除数组中的重复值,返回去重后数组元素的个数 4 int no_repeat(int a[], int n); 5 //如果x在数组a中,返回1,否则返回0 6 int if_in(int a[], int n, int x); 7 int main(void) 8 { 9 int i, n1, a[MAXN], n2, b[MAXN], count; 10 11 scanf("%d", &n1); 12 for (i = 0; i < n1; i++) 13 { 14 scanf("%d", &a[i]); 15 } 16 17 scanf("%d", &n2); 18 for (i = 0; i < n2; i++) 19 { 20 scanf("%d", &b[i]); 21 } 22 23 //去重后的长度 24 n1 = no_repeat(a, n1); 25 n2 = no_repeat(b, n2); 26 27 count = 0; 28 for (i = 0; i < n1; i++) 29 { 30 if (if_in(b, n2, a[i]) == 0) 31 { 32 count++; 33 if (count == 1) 34 { 35 printf("%d", a[i]); 36 } 37 else 38 { 39 printf(" %d", a[i]); 40 } 41 } 42 } 43 44 for (i = 0; i < n1; i++) 45 { 46 if (if_in(a, n1, b[i]) == 0) 47 { 48 count++; 49 if (count == 1) 50 { 51 printf("%d", b[i]); 52 } 53 else 54 { 55 printf(" %d", b[i]); 56 } 57 } 58 } 59 printf("\n"); 60 61 getchar(); 62 getchar(); 63 return 0; 64 } 65 int no_repeat(int a[], int n) 66 { 67 int i, j, k, len; 68 69 len = n; 70 for (i = n - 1; i > 0; i--) 71 { 72 for (j = 0; j < i; j++) 73 { 74 if (a[i] == a[j]) 75 { 76 len--; 77 for (k = i; k < len; k++) 78 { 79 a[k] = a[k + 1]; 80 } 81 break; 82 } 83 } 84 } 85 86 return len; 87 } 88 int if_in(int a[], int n, int x) 89 { 90 int i, result; 91 92 result = 0; 93 for (i = 0; i < n; i++) 94 { 95 if (a[i] == x) 96 { 97 result = 1; 98 break; 99 } 100 } 101 102 return result; 103 }