陣列的求交集和並集
阿新 • • 發佈:2020-08-16
遇到一個題目是求陣列的交集和並集,當時沒思考出來,現在靜下心來搞出來
package base0815_sendRedPacket; import java.util.ArrayList; public class Array { public static void main(String[] args) { int [] array1 = {1,3,4,6,8,9,15}; int [] array2 = {3,4,6,8,9,14}; //求陣列的交集 ArrayList<Integer> newList = new ArrayList<>(); for (int i = 0; i < array1.length; i++) { for (int i1 = 0; i1 < array2.length; i1++) { if (array1[i] == array2[i1]){ newList.add(array1[i]); } } } //輸出交集 System.out.println(newList.toString()); //求陣列並集 ArrayList<Integer> newList1 = new ArrayList<>(); for (int i = 0; i < array1.length; i++) { newList1.add(array1[i]); } for (int i = 0; i < array2.length; i++) { newList1.add(array2[i]); } for (int i = 0; i < newList.size(); i++) { newList1.remove(newList.get(i)); } // 輸出並集 System.out.println(newList1.toString()); } }