java solution using hashset


  • 0
    J

    Firstly,i sort two arrays.Then i use two pointers to iterate two arrays,if two elems is the same,then add it to the set.As you can see,the set stores the intersection of two arrays.

    public int[] intersection(int[] nums1, int[] nums2) {
            if(nums1==null || nums2==null){
                return null;
            }
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int len1=nums1.length;
            int len2=nums2.length;
            HashSet<Integer> set=new HashSet<Integer>();
            for(int i=0,j=0;i<len1 && j<len2;){
                if(nums1[i]<nums2[j]){
                    i++;
                }else if(nums1[i]>nums2[j]){
                    j++;
                }else{
                    set.add(nums1[i]);
                    i++;
                    j++;
                }
            }
            int[] nums3=new int[set.size()];
            int k=0;
            for(int num:set){
                nums3[k++]=num;
            }
            return nums3;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.