Java查找两个数组的交集

给定 两个排序后的数组,编写一个Java代码来查找两个数组的交集。

例如,如果输入数组是:

arr1 [] = {2,3,6,7,9,11 } 

arr2 [] = {4,6,8,9,12}

然后,您的程序应将交集打印为{6,9}。在编写实际代码之前,让我们首先讨论解决此问题的不同方法。

 

如何找到两个数组的交集

 

方法1(最简单或幼稚的方法):

在这种方法中,我们采用第一个数组的每个元素,并与第二个数组的每个元素进行比较。
这种方法的时间复杂度为O(mn),其中m和n是arr1 []和arr2 []中元素的数量。

 
1
2
3
4
5
6
7
8
   for(int i=0; i<arr1.length; i++ ) {
       for(int j=0; j<arr2.length; j++) {
           //If element is matched then print it
           if(arr1[i]==arr2[j]) {
              System.out.println(arr[j]);
            }
        }
    }

 

方法2:

i)使用两个索引变量i和j,将它们初始化为
0。ii)如果arr1 [i]小于arr2 [j],则递增i。
iii)如果arr1 [i]大于arr2 [j],则递增j。
iv)如果两者相同,则打印任何数组值并增加i和j。

此方法的时间复杂度为O(m + n)。

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Intersection {
 
   public static void main(String[] args) {
 
       int arr1[] = {2, 6, 7, 8, 9};
       int arr2[] = {6, 9, 10};
 
       /**
        Take two indexes,
        and initialize with zero.
       */
       int i = 0;
       int j = 0;
 
       while(i < arr1.length && j < arr2.length) {
         if(arr1[i] == arr2[j]) {
            System.out.println(arr1[i]);
            i++;
            j++;
         } else if(arr1[i] > arr2[j]) {
           j++;
         } else {
           i++;
        }
    }
  }
}

方法3:使用HashSet

在这种方法中,我们首先初始化一个空集合,然后遍历第一个数组并将第一个数组的每个元素放入一个集合中。现在,对于第二个数组的每个元素x,我们在集合中搜索x。如果存在x,则打印它。此方法的时间复杂度为O(m + n)。

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
  Using hashset to find intersection of two arrays
*/
public class Intersection {
 
   public static void main(String[] args) {
 
     int arr1[] = {2, 3, 4, 5, 6};
     int arr2[] = {4, 6, 7, 8, 9};
    
     //Declare hashset  
     HashSet<Integer> set1 = new HashSet();
    
     //Traverse an array, put each element in a set
     for(int val: arr1){
       set1.add(val);
     }
 
     /**
       Traverse second array values,
       Search the value in a set (set1),
       If element is found then print it.
     */
     for(int val: arr2){
       if(set1.contains(val)){
          System.out.println(val);
       }
    }
 
  }
}

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Intersection {
 
     public static void main(String[] args) {
 
        Integer arr1[] = {2, 3, 4, 5, 6};
        Integer arr2[] = {4, 6, 7, 8, 9};
        
        HashSet set1 = new HashSet<>(Arrays.asList(arr1));
        HashSet set2 = new HashSet<>(Arrays.asList(arr2));
 
        set1.retainAll(set2);
        System.out.println(set1);
    }
}

 

结论

我已经解释了多种方法来查找Java中两个数组的交集及其时间复杂度。如果您想讨论任何其他方法,请通过您的评论告诉我们。

 
 
 
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值