算法训练 集合运算
问题描述
给出两个整数集合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
1 2 3 4
对Arraylist排序用Collections.sort(list);
对集合set排序 先把set集合元素放到Arraylist中 再用collections排序
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.HashSet; 4 import java.util.Scanner; 5 import java.util.Set; 6 7 public class 集合运算 { 8 static int n; 9 static int m; 10 public static void main(String[] args) { 11 Scanner sc=new Scanner(System.in); 12 ArrayList<Integer> list1=new ArrayList<>(); 13 ArrayList<Integer> list2=new ArrayList<>(); 14 n=sc.nextInt(); 15 for(int i=0;i<n;i++){ 16 list1.add(sc.nextInt()); 17 } 18 m=sc.nextInt(); 19 for(int i=0;i<m;i++){ 20 list2.add(sc.nextInt()); 21 } 22 //求交集 23 ArrayList<Integer> list3=new ArrayList<>(); 24 for(int i:list1){ 25 for(int j:list2){ 26 if(i==j) { 27 list3.add(j); 28 break; 29 } 30 } 31 } 32 Collections.sort(list3); 33 //要从小到大输出 34 for(int m:list3){ 35 System.out.printf("%d ",m); 36 } 37 System.out.println(); 38 //求并集 39 Set<Integer> set1=new HashSet<>(); 40 for(int i:list1){ 41 set1.add(i); 42 } 43 for(int i:list2){ 44 set1.add(i); 45 } 46 //set集合排序 把set1放到Arraylist中 再用collections排序 47 ArrayList<Integer> list=new ArrayList<>(); 48 for(int m:set1){ 49 list.add(m); 50 } 51 Collections.sort(list); 52 for(int i:list){ 53 System.out.printf("%d ",i); 54 } 55 System.out.println(); 56 //求A-B 57 for(int j:list2){ 58 if(list1.contains(j)){ 59 int index=getindex(list1,j); 60 list1.remove(index); 61 } 62 } 63 Collections.sort(list1); 64 for(int m:list1){ 65 System.out.printf("%d ",m); 66 } 67 } 68 //返回元素j在list1中的下标 69 private static int getindex(ArrayList<Integer> list,int j) { 70 for(int i=0;i<list.size();i++){ 71 if(j==list.get(i)){ 72 return i; 73 } 74 } 75 return -1; 76 } 77 }