349. 两个数组的交集

方法一:使用set来存储2个数组的元素

时间O(m+n),空间O(m+n)

    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1==null || nums2==null || nums1.length==0 || nums2.length==0){
            return new int[0];
        }
        Set<Integer> parentSet = new HashSet<>();
        Set<Integer> childSet = new HashSet<>();
        for (int num:nums1){
            parentSet.add(num);
        }
        for (int num:nums2){
            // 根据题意,不需要重复元素
            if(parentSet.contains(num)){
                childSet.add(num);
            }
        }
        int[] arrays = new int[childSet.size()];
        int index=0;
        for(int num:childSet){
            arrays[index++]=num;
        }
        return arrays;
    }

方法二:排序+set

时间O(mlogm+nlogn)(取决于排序耗时),空间O(logn+logm)(取决于排序所需空间)

    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1==null || nums2==null || nums1.length==0 || nums2.length==0){
            return new int[0];
        }   
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        Set<Integer> set = new HashSet<Integer>();
        int i=0,j=0;
        while(i<nums1.length && j<nums2.length){
            if(nums1[i]==nums2[j]){
                set.add(nums1[i]);
                i++;
                j++;
            }else if(nums1[i]<=nums2[j]){
                i++;
            }else{
                j++;
            }
        }
        int[] arrays = new int[set.size()];
        int index=0;
        for(int num:set){
            arrays[index++]=num;
        }
        return arrays;
    }
争取早日不再是一只菜鸡
原文地址:https://www.cnblogs.com/jchen104/p/14684279.html