遇到一个题目是求数组的交集和并集,当时没思考出来,现在静下心来搞出来
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()); } }