如何在 Java 中找出兩個陣列的交集?


要找出 java 中的兩個陣列的交集,請使用兩個迴圈。外層迴圈用於迭代第一個陣列的元素,而第二個迴圈用於迭代第二個陣列的元素。在第二個迴圈中比較兩個陣列的元素

示例

動態演示

public class IntersectionOfTwoArrays {
   public static void main(String args[]) {
      int myArray1[] = {23, 36, 96, 78, 55};
      int myArray2[] = {78, 45, 19, 73, 55};
      System.out.println("Intersection of the two arrays ::");
     
      for(int i = 0; i<myArray1.length; i++ ) {
         for(int j = 0; j<myArray2.length; j++) {
            if(myArray1[i]==myArray2[j]) {
               System.out.println(myArray2[j]);
            }
         }
      }
   }
}

輸出

Intersection of the two arrays ::
78
55

更新於:16-6 月-2020

7K+ 瀏覽量

開啟您的 職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.