java定义俩个int类型数组求交集并集
时间: 2024-02-21 19:57:58 浏览: 73
可以使用Java中的Set集合来求解数组的交集和并集。
求交集:
```java
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {3, 4, 5, 6};
Set<Integer> set1 = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
set1.add(arr1[i]);
}
Set<Integer> set2 = new HashSet<Integer>();
for (int i = 0; i < arr2.length; i++) {
set2.add(arr2[i]);
}
set1.retainAll(set2);
int[] intersection = new int[set1.size()];
int index = 0;
for (Integer i : set1) {
intersection[index++] = i;
}
System.out.println(Arrays.toString(intersection)); // 输出 [3, 4]
```
求并集:
```java
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {3, 4, 5, 6};
Set<Integer> set1 = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
set1.add(arr1[i]);
}
Set<Integer> set2 = new HashSet<Integer>();
for (int i = 0; i < arr2.length; i++) {
set2.add(arr2[i]);
}
set1.addAll(set2);
int[] union = new int[set1.size()];
int index = 0;
for (Integer i : set1) {
union[index++] = i;
}
System.out.println(Arrays.toString(union)); // 输出 [1, 2, 3, 4, 5, 6]
```
阅读全文