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("
"); System.out.print("Array 2: "); for(int k = 0; k < n; k++) { System.out.print(arr2[k] + " "); } System.out.print("
"); 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("
"); 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++; } }
廣告