java输入两个数组,求他们的交集和异或集
时间: 2024-05-02 10:16:54 浏览: 95
下面是 Java 代码示例,用于输入两个数组,求它们的交集和异或集:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 第一个数组的长度
int m = sc.nextInt(); // 第二个数组的长度
int[] arr1 = new int[n];
int[] arr2 = new int[m];
for (int i = 0; i < n; i++) {
arr1[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
arr2[i] = sc.nextInt();
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
Set<Integer> xor = new HashSet<>();
for (int i = 0; i < n; i++) {
set1.add(arr1[i]);
}
for (int i = 0; i < m; i++) {
set2.add(arr2[i]);
}
for (int num : set1) {
if (set2.contains(num)) {
intersect.add(num);
}
xor.add(num);
}
for (int num : set2) {
xor.add(num);
}
for (int num : intersect) {
xor.remove(num);
}
System.out.println("Intersection: " + intersect);
System.out.println("Xor: " + xor);
}
}
```
示例输入:
```
5 7
1 2 3 4 5
3 4 5 6 7 8 9
```
示例输出:
```
Intersection: [3, 4, 5]
Xor: [1, 2, 6, 7, 8, 9]
```
阅读全文