用c++编写程序,输入两个集合的元素(分别保存到数组,注意一个集合中的元素不能重复),
求出它们的并集。例如,有集合a={1,3,5,7,9}, b={1,2,5,4,6},并集c={1,3,5,7,9,2,4,6}。设计
时,可以先将一个数组的所有元素存入并集中,对另一个集合的每个元素逐个进行判别:若
不属于并集则加入其中
我的代码:
#include <iostream> #include <algorithm> using namespace std; //检查b是否在数组a中 inline bool f1(int *a, int size_a,int b) { if (b < a[0] || b > a[size_a-1]) return 1; for (int j = 0; j < size_a; ++j) { if (a[j] == b) { return 0; } } return 1; } void merge_array(int *a, int size_a,int *b, int size_b,int *c,int &merge_size) { bool flag = 1;//数组a大则为1 int real_size = 0; if (size_a > size_b) sort(a,a+size_a); else { sort(b,b+size_b); flag = 0; } if (flag) { real_size = size_a; for (int i = 0; i < size_a; ++i) { c[i] = a[i]; } for (int i = 0; i < size_b;++i) { if (f1(a,size_a,b[i])) { c[real_size++] = b[i]; } } } else { real_size = size_b; for (int i = 0; i < size_b; ++i) { c[i] = b[i]; } for (int i = 0; i < size_a;++i) { if (f1(b,size_b,a[i])) { c[real_size++] = a[i]; } } } merge_size = real_size; } int main() { int a[] = {1,3,5,7,9}, b[] = {1,2,5,4,6}; int size_a = sizeof(a)/sizeof(*a), size_b = sizeof(b)/sizeof(*b); int merge_size = size_a + size_b; int *c = new int[merge_size]; merge_array(a,size_a,b,size_b,c,merge_size); for (int i = 0 ; i < merge_size; ++i) { cout << c[i]<< " "; } }