給定兩個整數數組:
arr1 = [1, 3, 4, 5, 8, 9] arr2 = [2, 3, 7, 8, 9]
求它們的 交集、並集 與 差集。
removeAll 去重後合併。import java.util.ArrayList;
import java.util.Collections;
public class ArraySetOperations {
public static void main(String[] args) {
int[] arr1 = {1, 3, 4, 5, 8, 9};
int[] arr2 = {2, 3, 7, 8, 9};
ArrayList result = intersection(arr1, arr2);
printResult("交集", result);
result = union(arr1, arr2);
printResult("並集", result);
result = difference(arr1, arr2);
printResult("差集 (arr1 - arr2)", result);
}
// 交集
private static ArrayList intersection(int[] a1, int[] a2) {
ArrayList list = new ArrayList<>();
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
list.add(a1[i]);
}
}
}
return list;
}
// 並集
private static ArrayList union(int[] a1, int[] a2) {
ArrayList list1 = new ArrayList<>();
ArrayList list2 = new ArrayList<>();
for (int v : a1) list1.add(v);
for (int v : a2) list2.add(v);
list1.removeAll(list2); // 移除 list2 中已有的元素
list2.addAll(list1); // 合併剩餘元素
return list2;
}
// 差集 (a1 - a2)
private static ArrayList difference(int[] a1, int[] a2) {
ArrayList list1 = new ArrayList<>();
ArrayList list2 = new ArrayList<>();
for (int v : a1) list1.add(v);
for (int v : a2) list2.add(v);
list1.removeAll(list2); // 保留只在 a1 中的元素
return list1;
}
private static void printResult(String label, ArrayList list) {
Collections.sort(list);
System.out.print(label + ":");
if (list.isEmpty()) {
System.out.println("null");
} else {
for (int v : list) System.out.print(v + " ");
System.out.println();
}
}
}
交集:3 8 9 並集:1 2 3 4 5 7 8 9 差集 (arr1 - arr2):1 4 5
若數據量大,雙重循環 O(n²) 效率較低。可優化為:
HashSet,查找時間降為 O(1),總體 O(n)。Arrays.stream(arr1).filter(x -> Arrays.stream(arr2).anyMatch(y -> y == x)).collect(Collectors.toList())。