Java中两个数组的交集

两个数组的交集导致两个数组中都包含这些元素。如果元素仅在数组之一中,则在交集中不可用。一个例子如下:

Array 1 = 1 2 5 8 9
Array 2 = 2 4 5 9
Intersection = 2 5 9

给出了一个演示Java中两个排序数组的交集的程序,如下所示。

示例

public class Example {
   public static void main(String args[]) {
      int arr1[] = {2, 4, 6, 8, 9};
      int arr2[] = {1, 3, 4, 5, 6, 8, 9};
      int m = arr1.length;
      int n = arr2.length;
      int i = 0, j = 0;
      System.out.print("Array 1: ");
      for(int k = 0; k < m; k++) {
         System.out.print(arr1[k] + " "); 
      }
      System.out.print("\n");
      System.out.print("Array 2: ");
      for(int k = 0; k < n; k++) {
         System.out.print(arr2[k] + " ");
      }
      System.out.print("\n");
      System.out.print("Intersection of two arrays is: ");
      while (i < m && j < n) {
         if (arr1[i] < arr2[j])
            i++;
         else if (arr2[j] < arr1[i])
            j++;
         else {
            System.out.print(arr2[j++]+" ");
            i++; 
         }
      }
   }
}

上面程序的输出如下。

输出结果

Array 1: 2 4 6 8 9
Array 2: 1 3 4 5 6 8 9
Intersection of two arrays is: 4 6 8 9

现在让我们了解上面的程序。

首先,打印两个数组的值。演示此过程的代码段如下所示。

System.out.print("Array 1: ");
for(int k = 0; k < m; k++) {
   System.out.print(arr1[k] + " ");
}
System.out.print("\n");
System.out.print("Array 2: ");
for(int k = 0; k < n; k++) {
   System.out.print(arr2[k] + " ");
}

然后,使用while循环显示两个数组的交集,即它们的公共元素。演示此过程的代码段如下所示。

System.out.print("Intersection of two arrays is: ");
while (i < m && j < n) {
   if (arr1[i] < arr2[j])
      i++;
   else if (arr2[j] < arr1[i])
      j++;
   else {
      System.out.print(arr2[j++]+" ");
      i++;
   }
}