JAVA 蓝桥杯 算法训练 集合运算
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
输入格式
第一行为一个整数n,表示集合A中的元素个数。
第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
第三行为一个整数m,表示集合B中的元素个数。
第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
集合中的所有元素均为int范围内的整数,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.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sca=new Scanner(System.in);
int n=sca.nextInt();
HashSet<Integer> set=new HashSet<Integer>();
ArrayList<Integer> array=new ArrayList<Integer>();
ArrayList<Integer> array2=new ArrayList<Integer>();
ArrayList<Integer> array3=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
int a=sca.nextInt();
set.add(a);
array.add(a);
}
int m=sca.nextInt();
for(int j=0;j<m;j++) {
int a=sca.nextInt();
set.add(a);
if(array.contains(a)) {
array2.add(a);
}
}
Collections.sort(array);
Collections.sort(array2);
for(Integer in:array2) {
System.out.print(in+" ");
}
System.out.println();
Iterator<Integer> iter=set.iterator();
while(iter.hasNext()) {
array3.add(iter.next());
}
Collections.sort(array3);
for(Integer in:array3) {
System.out.print(in+" ");
}
System.out.println();
for(Integer in:array) {
if(!array2.contains(in)) {
System.out.print(in+" ");
}
}
}
}