解题思路:
我才用了ArrayList,就不需要自己写交并差查找的算法了,用的是Java8 Stream
具体实现参考了Qblue666的文章https://blog.csdn.net/sunpanlong123/article/details/126870335
可以把这个改成此类问题的模板使用
参考代码:
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n1=sc.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for(int i=0;i<n1;i++) { int x=sc.nextInt(); a.add(x); } int n2=sc.nextInt(); ArrayList<Integer> b = new ArrayList<Integer>(); for(int i=0;i<n2;i++) { int x=sc.nextInt(); b.add(x); } //a*b交集 List<Integer> jiao = a.stream().filter(b::contains).collect(Collectors.toList()); Collections.sort(jiao); System.out.println(Arrays.toString(jiao.toArray()).replace("[", "").replace("]", "").replace(",", ""));//控制输出不带[ ]和',' //a+b并集 ArrayList<Integer> bing = new ArrayList<Integer>(); bing.addAll(a); bing.removeAll(b);//先从本集合中删除另一个集合中相同的元素 bing.addAll(b);//再把另外一个集合中所有元素,添加到本集合中 Collections.sort(bing); System.out.println(Arrays.toString(bing.toArray()).replace("[", "").replace("]", "").replace(",", "")); //a-b的差集 List<Integer> cha = a.stream().filter(i -> !b.contains(i)).collect(Collectors.toList()); Collections.sort(cha); System.out.println(Arrays.toString(cha.toArray()).replace("[", "").replace("]", "").replace(",", "")); } }
0.0分
1 人评分
C二级辅导-公约公倍 (C语言代码)浏览:2123 |
C语言程序设计教程(第三版)课后习题8.6 (C语言代码)浏览:582 |
【绝对值排序】 (C语言代码)浏览:717 |
分糖果 (C++代码)浏览:1451 |
Wu-求圆的面积 (C++代码)浏览:1899 |
C语言程序设计教程(第三版)课后习题6.5 (C++代码)浏览:458 |
【求[X,Y]内被除3余1并且被除5余3的整数的和】 (C语言代码)浏览:675 |
求圆的面积 (C语言代码)浏览:1672 |
愚蠢的摄影师 (C++代码)浏览:939 |
简单的a+b (C语言代码)浏览:488 |