题目:给出两个数组,分别求出这两个数组的交集,并集和补集
思路:主要还是利用了HashSet的去重功能,在set中不存在相同的元素
代码:
public class Substract { public static void substract(int[] arryA, int[] arryB) { HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arryA.length; i++) { //if(!list.contains(arryA[i])) set.add(arryA[i]); } for (int j = 0; j < arryB.length; j++) { if (set.contains(arryB[j])) set.remove(arryB[j]); } for (int temp : set) { System.out.print(temp + " "); } } //求两个数组的并集 public static void union(int arryA[], int arryB[]) { HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arryA.length; i++) { set.add(arryA[i]); } for (int j = 0; j < arryB.length; j++) { set.add(arryB[j]); } for (int temp : set) { System.out.print(temp + " "); } } //两个数组的交集 public static void intersect(int arryA[], int arryB[]) { HashSet<Integer> set = new HashSet<Integer>(); HashSet<Integer> res = new HashSet<Integer>(); for (int i = 0; i < arryA.length; i++) { if (!set.contains(arryA[i])) set.add(arryA[i]); } for (int j = 0; j < arryB.length; j++) { if (set.contains(arryB[j])) res.add(arryB[j]); } for (int temp : res) { System.out.print(temp + " "); } } public static void main(String args[]){ int arryA[]={1,2,3,4,5,6,7,8}; int arryB[]={1,2,3}; //substract(arryA,arryB); //union(arryA,arryB); intersect(arryA, arryB); } }