可以使用HashSet来求多个数组之间的交集。具体步骤如下:
- 将第一个数组转换为HashSet。
- 遍历其他数组,将其中的元素添加到第一个数组的HashSet中。
- 最后HashSet中就是所有数组的交集。
下面是一个示例代码:
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
int[] arr3 = {5, 6, 7, 8, 9};
Set<Integer> set = new HashSet<>();
for (int num : arr1) {
set.add(num);
}
for (int i = 1; i < 3; i++) {
Set<Integer> tempSet = new HashSet<>();
for (int num : set) {
if (contains(arr2, num) && contains(arr3, num)) {
tempSet.add(num);
}
}
set = tempSet;
}
System.out.println("Intersection of arrays: " + set);
}
public static boolean contains(int[] arr, int num) {
for (int i : arr) {
if (i == num) {
return true;
}
}
return false;
}
}
注意:这段代码中使用了一个contains方法来判断一个数组中是否包含某个元素,这样可以方便地判断元素是否在所有数组中出现。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/919074.html