12.LeetCode:Intersection of Two Arrays

题目: 

12.LeetCode:Intersection of Two Arrays

使用集合: 

public class IntersectionOfArraySolution {
    public int[] intersection(int[] nums1, int[] nums2) {
        TreeSet<Integer> set = new TreeSet<>();
        for (int num:nums1) {
            set.add(num);
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int num:nums2) {
            if(set.contains(num)){
                list.add(num);
                //num2可能有重复的元素,如果不移除set的num,必然下次又匹配了
                set.remove(num);
            }
        }
        int[] res = new int[list.size()];
        for (int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
        return res;
    }
}