计算集合的并 set
2018-02-28 18:00
183 查看
问题描述
给你两个集合,计算其并集,即{A}+{B}。注:{A}+{B}中不允许出现重复元素,但是{A} 与{B}之间可能存在相同元素。
输入格式
输入数据分为三行,第一行有两个数字n,m(0< n,m≤10000),分别表示集合 A 和集合 B 的元素个数。后两行分别表示集合 A 和集合 B。每个元素为不超出 int 范围的整数,每个元素之间用一个空格隔开。
输出格式
输出一行数据,表示合并后的集合,要求从小到大输出,每个元素之间用一个空格隔开。
样例输入
1 2
1
2 3
样例输出
1 2 3
set集合是由不重复的数据组成的。set的插入、删除、查询的时间复杂度都是O(lgn)。数组插入的时间复杂度是O(1),删除查询是O(n)。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <set>
using namespace std;
const int inf=0x3f3f3f3f;
int main(){
int a,b;
set<int>st1,st2;
scanf("%d%d",&a,&b);
for(int i=1;i<=a;i++){
int t;
scanf("%d",&t);
st1.insert(t);//插入顺序和存储顺序无关,按从小到大存储;如集合中已经存在插入的数据,不会再次插入
}
for(int i=1;i<=b;i++){
int t;
scanf("%d",&t);
st2.insert(t);
}
//使用迭代器遍历
for(set<int>::iterator it=st1.begin();it!=st1.end();it++){
int t=*it;
printf("%d ",t);
if(st2.count(t))/*查找:存在返回1*/ st2.erase(t);/*删除t*//*.clear()清空*/
}
if(!st2.empty())
for(set<int>::iterator it=st2.begin();it!=st2.end();it++)
printf("%d ",*it);
printf("\n");
return 0;
}
/*
1 2
1
2 3
*/
相关文章推荐
- 使用set集合出来list列表的计算
- Morphological and Other Set Operations(图像形态学及集合计算)
- 8-计算集合的并集(set)
- 09.集合框架(二)【Set】【HashSet】【TreeSet】
- 快速学习stl中集合set
- 驯服 Tiger: 并发集合 超越 Map、Collection、List 和 Set
- python set集合
- Java 中的集合接口——List、Set、Map
- set集合完整版整理
- 黑马程序员——JAVA基础之set集合
- Day07 set集合与map集合
- list、set、map集合的综合应用
- 认识python中的set集合及其用法
- 黑马程序员_Java集合概述和Set集合
- 解决springMVC对象中包含Set集合的问题
- Python 集合 set
- spring利用set操作对引用类型和集合类型进行注入值
- 【14】集合1_集合框架,迭代器,List集合,Set集合
- List、Set集合遍历方式
- Redis 集合(Set)