java怎么求多个数组之间的交集


可以使用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方法来判断一个数组中是否包含某个元素,这样可以方便地判断元素是否在所有数组中出现。


上一篇:c语言常量定义的规则有哪些

下一篇:php indexof函数的作用是什么


Java
Copyright © 2002-2019 测速网 https://www.inhv.cn/ 皖ICP备2023010105号 城市 地区 街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
热门搜索