Java不用Hash函数取两个int数组的交集和并集
时间: 2024-02-21 14:00:03 浏览: 62
如果不使用`HashSet`和`HashMap`等哈希函数,可以使用双指针来求取两个int数组的交集和并集。代码如下:
```java
public class ArrayIntersectionUnion {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 4, 5, 6, 7, 8 };
// 求交集
List<Integer> intersection = new ArrayList<>();
int i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
i++;
} else if (arr1[i] > arr2[j]) {
j++;
} else {
intersection.add(arr1[i]);
i++;
j++;
}
}
System.out.println("Intersection: " + intersection);
// 求并集
List<Integer> union = new ArrayList<>();
i = 0;
j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
union.add(arr1[i]);
i++;
} else if (arr1[i] > arr2[j]) {
union.add(arr2[j]);
j++;
} else {
union.add(arr1[i]);
i++;
j++;
}
}
while (i < arr1.length) {
union.add(arr1[i]);
i++;
}
while (j < arr2.length) {
union.add(arr2[j]);
j++;
}
System.out.println("Union: " + union);
}
}
```
运行结果与使用哈希函数求取的结果一致:
```
Intersection: [4, 5]
Union: [1, 2, 3, 4, 5, 6, 7, 8]
```
阅读全文