Javascript solution with two pointers


  • 0
    R
    var intersection = function(nums1, nums2) {
        var res = [],
            last,
            i = 0,
            j = 0;
        
        nums1.sort(function(a, b){
            return a - b;
        });
        
        nums2.sort(function(a, b){
            return a - b;
        });
        
        while(i < nums1.length && j < nums2.length){
            if(nums1[i] === nums2[j]){
                if(nums1[i] !== last){
                    res.push(nums1[i]);
                    last = nums1[i];
                }
                i++;
                j++;
            }
            if(nums1[i] > nums2[j])
                j++;
            if(nums1[i] < nums2[j])
                i++;
        }
        
        return res;
    };

Log in to reply
 

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