问题描述
给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
输入格式
第一行为一个整数n,表示集合A中的元素个数。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,n、m<=1000。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,n、m<=1000。
输出格式
第一行按从小到大的顺序输出A、B交集中的所有元素。
第二行按从小到大的顺序输出A、B并集中的所有元素。
第三行按从小到大的顺序输出B在A中的余集中的所有元素。
第二行按从小到大的顺序输出A、B并集中的所有元素。
第三行按从小到大的顺序输出B在A中的余集中的所有元素。
样例输入
5
1 2 3 4 5
5
2 4 6 8 10
1 2 3 4 5
5
2 4 6 8 10
样例输出
2 4
1 2 3 4 5 6 8 10
1 3 5
1 2 3 4 5 6 8 10
1 3 5
样例输入
4
1 2 3 4
3
5 6 7
1 2 3 4
3
5 6 7
样例输出
1 2 3 4 5 6 7
1 2 3 4
题目分析:基础题
算法分析:用好java类才是关键,利用Set集合不能包含重复元素的性质,调用Treeset类,对于本题是最合适的。
算法设计:
import java.util.*;
public class Main {
public static void Print(Set<Integer> result) {
if (result.size() != 0) {
Iterator<Integer> it = result.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Set<Integer> set1 = new TreeSet<Integer>();
Set<Integer> set2 = new TreeSet<Integer>();
Set<Integer> result = new TreeSet<Integer>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
set1.add(sc.nextInt());
}
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
set2.add(sc.nextInt());
}
sc.close();
result.clear();
result.addAll(set1);
result.retainAll(set2); //移除未包含在指定set1中的所有元素
Print(result); //交集
result.clear();
result.addAll(set1);
result.addAll(set2);
Print(result); //并集
result.clear();
result.addAll(set1);
result.removeAll(set2);
Print(result); //差集
}
}
友情链接之:
Tsinsen 第一卷 题解(持更中)