将两个整型数组按照升序合并,并且过滤掉重复数组元素
时间: 2023-03-28 11:01:41 浏览: 66
可以使用以下代码实现:
```c
#include <stdio.h>
void merge(int arr1[], int n1, int arr2[], int n2, int merged[]) {
int i = , j = , k = ;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else if (arr1[i] > arr2[j]) {
merged[k++] = arr2[j++];
} else {
merged[k++] = arr1[i++];
j++;
}
}
while (i < n1) {
merged[k++] = arr1[i++];
}
while (j < n2) {
merged[k++] = arr2[j++];
}
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int n1 = sizeof(arr1) / sizeof(arr1[]);
int arr2[] = {2, 4, 6, 8, 10};
int n2 = sizeof(arr2) / sizeof(arr2[]);
int merged[n1 + n2];
merge(arr1, n1, arr2, n2, merged);
for (int i = ; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
return ;
}
```
输出结果为:1 2 3 4 5 6 7 8 9 10
其中,merge 函数用于合并两个数组,merged 数组用于存储合并后的结果。在合并过程中,如果遇到相同的元素,则只保留一个。
阅读全文