您的位置:首页 > 其它

【题目39】整数集合的并差交集

2009-10-12 14:12 274 查看
题目:两个整数集合A,B,求其并集,交集,差集,对称差集,要求写出代码

分析: 首先对数组进行排序,如果数组无序的话。

具体可以参考侯捷《STL源码解析》的方法实现。我这里就是参照那里的方

法实现的。详情请见源码。

例子: A: 1 3 5 7 9 11

B: 1 1 2 3 5 8 13

Union of A and B: 1 1 2 3 5 7 8 9 11 13

Intersection of A and B: 1 3 5

Difference of A and B(A-B): 7 9 11

Difference of B and A(B-A): 1 2 7 8 9 11 13

Symmetric difference of A and B: 1 2 7 8 8 11 13

源码如下:

#include <stdio.h>
#define N 100
int result
;

void set_union(int* a, int lenA,int* b,int lenB)
{
int i = 0, j = 0,k = 0;
while(true)
{
if(a[i] < b[j])
{
result[k++] = a[i];
i++;
}
else if(a[i] > b[j])
{
result[k++] = b[j];
j++;
}
else
{
result[k++] = a[i];
i++;
j++;
}
if(i >= lenA || j >= lenB)
break;
}
while(i < lenA)
{
result[k++] = a[i];
i++;
}
while(j < lenB)
{
result[k++] = b[j];
j++;
}
}

void set_intersection(int* a, int lenA,int* b,int lenB)
{
int i = 0, j = 0,k = 0;
while(true)
{
if(a[i] < b[j])
{
i++;
}
else if(a[i] > b[j])
{
j++;
}
else
{
result[k++] = a[i];
i++;
j++;
}
if(i >= lenA || j >= lenB)
break;
}
}

void set_difference(int* a, int lenA,int* b,int lenB)
{
int i = 0, j = 0,k = 0;
while(true)
{
if(a[i] < b[j])
{
result[k++] = a[i];
i++;
}
else if(a[i] > b[j])
{
j++;
}
else
{
i++;
j++;
}
if(i >= lenA || j >= lenB)
break;
}
while(i < lenA)
{
result[k++] = a[i];
i++;
}
}

void set_symmetric_difference(int* a, int lenA,int* b,int lenB)
{
int i = 0, j = 0,k = 0;
while(true)
{
if(a[i] < b[j])
{
result[k++] = a[i];
i++;
}
else if(a[i] > b[j])
{
result[k++] = b[j];
j++;
}
else
{
i++;
j++;
}
if(i >= lenA || j >= lenB)
break;
}
while(i < lenA)
{
result[k++] = a[i];
i++;
}
while(j < lenB)
{
result[k++] = b[j];
j++;
}
}

void InitArray(int *a,int n)
{
for(int i = 0; i < n; i++)
a[i] = -1;
}
void PrintArray(int* a, int n)
{
for(int i = 0; i < n; i++)
{
if(a[i] == -1)
break;
else
printf("%d ",a[i]);
}
printf("/n");
}
int main()
{
//if not sorted, sort it first
int A[6] = {1, 3,5,7,9,11};
int B[7] = {1,1,2,3,5,8,13};
InitArray(result,N);
set_union(A,6,B,7);
PrintArray(result,N);

InitArray(result,N);
set_intersection(A,6,B,7);
PrintArray(result,N);

InitArray(result,N);
set_difference(A,6,B,7);
PrintArray(result,N);

InitArray(result,N);
set_difference(B,7,A,6);
PrintArray(result,N);

InitArray(result,N);
set_symmetric_difference(A,6,B,7);
PrintArray(result,N);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: