8 集合运算
作者: Turbo时间限制: 1S章节: 基本练习(数组)
问题描述 :
给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
输入说明 :
第一行为一个整数n,表示集合A中的元素个数。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,1<=n、m<=1000。
输出说明 :
第一行按从小到大的顺序输出A、B交集中的所有元素。(如果交集为空,则没有这一行)
第二行按从小到大的顺序输出A、B并集中的所有元素。
第三行按从小到大的顺序输出B在A中的余集中的所有元素。(如果余集为空,则没有这一行)
样例输入
5
1 2 3 4 5
5
2 4 6 8 10
样例输出
2 4
1 2 3 4 5 6 8 10
1 3 5
输入范例 :
4
1 2 3 4
3
5 6 7
输出范例 :
1 2 3 4 5 6 7
1 2 3 4
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class test_58 {
/**
* 58 集合运算
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int alen = sc.nextInt();
sc.nextLine();
String[] splitA = sc.nextLine().trim().split(" ");
int blen = sc.nextInt();
sc.nextLine();
String[] splitB = sc.nextLine().trim().split(" ");
//存入数据
Set<Integer> a = new TreeSet<Integer>();
Set<Integer> middle = new TreeSet<Integer>();
Set<Integer> b = new TreeSet<Integer>();
for (int i = 0; i < splitA.length; i++) {
a.add(Integer.valueOf(splitA[i]));
}
for (int i = 0; i < splitB.length; i++) {
b.add(Integer.valueOf(splitB[i]));
}
//交
middle.addAll(a);
middle.retainAll(b);
removeData(middle);
//并集
middle.addAll(a);
middle.addAll(b);
removeData(middle);
//差
middle.addAll(a);
middle.removeAll(b);
removeData(middle);
}
private static void removeData(Set<Integer> a) {
if(a.size()>0){
Iterator<Integer> iterator = a.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
iterator.remove();
}
System.out.println();
}
}
}