数组的去重、并集、交集

蒟蒻的第二篇博客
数组的去重数组的去重、并集、交集_第1张图片
#include//C++万能头文件
using namespace std;
void unique(int a[], int n);
int a1[10000], a2[10000];
int main()
{
int n1, n2;
cin >> n1 >> n2;
for (int i = 0; i < n1; i++)
cin >> a1[i];
for (int i = 0; i < n2; i++)
cin >> a2[i];
unique(a1, n1);
unique(a2, n2);
return 0;
}
void unique(int a[], int n)//去重函数
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)
{
if (a[i] == a[j])
break;
}
if (i == j)
cout << a[i] << " ";
}
cout << endl;
}
求交集
数组的去重、并集、交集_第2张图片
#include
using namespace std;
int b[10000], c[10000];
int a1[10000], a2[10000], a3[10000];
void setinter(int a[], int b[], int n1, int n2);
int unique(int a[], int n);
int main()
{
int n1, n2, n3;
int x = 0, y = 0;
int k = 0, l = 0;
cin >> n1 >> n2 >> n3;
for (int i = 0; i < n1; i++)
cin >> a1[i];
for (int i = 0; i < n2; i++)
cin >> a2[i];
for (int i = 0; i < n3; i++)
cin >> a3[i];
setinter(a1, a2, n1, n2);
setinter(a1, a3, n1, n3);
return 0;
}
void setinter(int a[], int b[], int n1, int n2)//求交集
{
int c[10000], i, j, na, k = 0;
na = unique(a, n1);
for (i = 0; i < na; i++)
{
for (j = 0; j < n2; j++)
{
if (a[i] == b[j])
{
c[k++] = a[i];
break;
}
}
}
for (i = 0; i < k; i++)
cout << c[i] << " ";
cout << endl;
}
int unique(int a[],int n)//去重
{
int i, j, k = 0, flag = 1;
for (i = 0; i < n; i++)
{
for (j = i - 1; j >= 0; j–)
{
if (a[j] == a[i])
{
k++;
flag = 0;
}
if (flag == 1)
a[i - k] = a[i];
}
}
return n-k;
}
求并集
数组的去重、并集、交集_第3张图片
#include
using namespace std;
int a1[10000], a2[10000], a3[10000];
void Unique(int a[], int n);
void SetUnion(int a[], int b[], int m, int n);
int main()
{
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
for (int i = 0; i < n1; i++)
cin >> a1[i];
for (int i = 0; i < n2; i++)
cin >> a2[i];
for (int i = 0; i < n3; i++)
cin >> a3[i];
SetUnion(a1, a2, n1, n2);
SetUnion(a1, a3, n1, n3);
return 0;
}
void SetUnion(int a[], int b[], int m, int n)//求并集
{
int i, j, c[10000], k = 0;
for (i = 0; i < m; i++)
c[k++] = a[i];
for (j = 0; j < n; j++)
c[k++] = b[j];
Unique(c, k);
}
void Unique(int a[], int n)//数组的去重
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)
{
if (a[i] == a[j])
break;
}
if (i == j)
cout << a[i] << " ";
}
cout << endl;
}
感觉这些函数以后用经常使用:)

你可能感兴趣的:(数组的去重、并集、交集)