java从标准输入中输入两组整数(每组不超过20个整数,每组整数中的元素不重复,并且整数大于等于0),编程求两组整数的交集,即在两组整数中都出现的整数,并按从小到大顺序排序输出。若交集为空,则什么都不输出。
时间: 2023-04-09 15:00:55 浏览: 172
可以回答这个问题。以下是Java代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
Set<Integer> intersection = new TreeSet<>();
// 读入第一组整数
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());
}
// 求交集
for (int num : set1) {
if (set2.contains(num)) {
intersection.add(num);
}
}
// 输出结果
if (intersection.isEmpty()) {
// 交集为空,什么都不输出
} else {
for (int num : intersection) {
System.out.print(num + " ");
}
}
}
}
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)