Java 中找出两个数组的交集370


在 Java 中,找出两个数组的交集是一个常见的问题。交集是指同时存在于两个数组中的元素。

使用 Set

使用 Set 数据结构是找出交集的最简单方法之一。Set 是一个无序集合,它不会存储重复的元素。我们可以将两个数组都添加到 Set 中,然后使用 Set 的 retainAll 方法来保留两个数组的交集。
import ;
import ;
import ;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
// 将数组添加到 Set 中
Set set1 = new HashSet((arr1));
Set set2 = new HashSet((arr2));
// 保留交集
(set2);
// 打印交集
(set1);
}
}

使用双指针

如果我们知道两个数组都是升序排列的,我们可以使用双指针算法。我们从两个数组的开头开始,如果当前元素相等,则将其添加到交集中。如果一个元素较小,则我们移动该元素对应的指针。继续此过程,直到到达两个数组的末尾。
public static int[] intersection(int[] arr1, int[] arr2) {
int m = ;
int n = ;
int[] intersection = new int[m + n];
int i = 0, j = 0, k = 0;
while (i < m && j < n) {
if (arr1[i] == arr2[j]) {
intersection[k++] = arr1[i];
i++;
j++;
} else if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
return (intersection, 0, k);
}

使用 HashMap

我们可以使用 HashMap 来找出数组的交集。我们将一个数组的元素作为 Key,另一个数组的元素作为 Value。然后,遍历第一个数组,如果某个元素在 HashMap 中,则将其添加到交集中。这种方法的时间复杂度为 O(m + n),其中 m 和 n 是两个数组的长度。
public static int[] intersection(int[] arr1, int[] arr2) {
Map map = new HashMap();
for (int num : arr1) {
(num, 1);
}
List intersection = new ArrayList();
for (int num : arr2) {
if ((num)) {
(num);
}
}
return ().mapToInt(i -> i).toArray();
}


在 Java 中找出两个数组的交集有多种方法。选择最适合您特定要求的方法。使用 Set 的方法是最简单的,但仅适用于无重复元素的数组。使用双指针的方法是最有效的,但要求数组是有序的。使用 HashMap 的方法是最通用的,适用于任何类型的数组。

2024-12-07


上一篇:使用 Java 捕获数据包

下一篇:JSON 字符串与 Java Map 之间转换的最佳实践