计算集合的并集(stl—set)

ou_fan

给你两个集合,计算其并集,即{A}+{B}。
注意:{A}+{B}中不允许出现重复元素,但是{A}与{B}之间可能存在相同的元素。

输入格式
输入数据分为三行,第一行有两个数字n,m(0<n,m<10000),分别表示集合A和集合B的元素个数。后两行分别表示集合{A}和集合{B}。每个元素为不超过int范围的整数,每个元素之间用空格隔开。

输出格式
输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间用一个空格隔开。

样例输入1
1 2
1
2 3
样例输出1
1 2 3

样例输入2
1 2
1
1 2
样例输出2
1 2


分析:集合问题又要从小到大排序,且需要去重,所以使用set容器;

#include<bits/stdc++.h>
using namespace std;
set<int>arr;
int main() {
	int n, m;
	cin >> n >> m;
	//首先将第一个集合读入set
	for (int i = 0;i < n;i++) {
		int num;
		cin >> num;
		arr.insert(num);
	}
	//第二个集合,先查找有没有,再插入进去。
	for (int i = 0;i < m;i++) {
		int num;
		cin >> num;
		if (arr.count(num)) continue;
		else arr.insert(num);
	}
	for (auto it = arr.begin();it != arr.end();it++) {
		if (it != arr.begin()) cout << ' ';
			cout << *it;
	}
	return 0;
}

 反思:set会自动查重,所以不用做判断;

简便代码:

#include<bits/stdc++.h>
using namespace std;
set<int>arr;
int main() {
	int n, m;
	cin >> n >> m;
	//首先将第一个集合读入set
	for (int i = 0;i < n+m;i++) {
		int num;
		cin >> num;
		arr.insert(num);
	}
	for (auto it = arr.begin();it != arr.end();it++) {
		if (it != arr.begin()) cout << ' ';
			cout << *it;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ou_fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值