My 4ms Java solution


  • 0
    A
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1.length==0 || nums2.length == 0)return new int[0];
        
        int[] intersection = new int[nums1.length < nums2.length ? nums1.length : nums2.length];
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int p1 = 0, p2 = 0, curr = 0;
        while(p1<nums1.length && p2<nums2.length){
            if(nums1[p1] > nums2[p2])p2++;
            else if(nums1[p1] < nums2[p2])p1++;
            else{
                if(curr==0 || intersection[curr-1]!=nums1[p1])intersection[curr++] = nums1[p1];
                p1++;
                p2++;
            }
        }
        
        int[] result = new int[curr];
        for(int i=0; i<curr; i++){
            result[i] = intersection[i];
        }
        
        return result;
         
    }

Log in to reply
 

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