C语言求两组整数的交集
时间: 2023-11-28 21:05:42 浏览: 94
求两个数组的交集
以下是C语言求两组整数的交集的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int *)b - *(int *)a;
}
int main() {
int n, m;
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &m);
int *b = (int *)malloc(m * sizeof(int));
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
}
qsort(a, n, sizeof(int), cmp);
qsort(b, m, sizeof(int), cmp);
int *c = (int *)malloc(n * sizeof(int));
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i] == b[j]) {
c[k++] = a[i];
break;
}
}
}
if (k == 0) {
return 0;
}
qsort(c, k, sizeof(int), cmp);
for (int i = 0; i < k; i++) {
printf("%d ", c[i]);
}
free(a);
free(b);
free(c);
return 0;
}
```
阅读全文