Javascript solution - two pointers


  • 0
    R
    var intersect = function(nums1, nums2) {
        var res = [],
            i = 0,
            j = 0;
        
        // Sort nums1
        nums1.sort(function(a, b){ 
            return a - b; 
        });
        
        // Sort nums2
        nums2.sort(function(a, b){ 
            return a - b; 
        });
        
        // Traverse through two pointers
        while(j < nums2.length && i < nums1.length){
            if(nums1[i] === nums2[j]){
                res.push(nums2[j]);
                j++;
                i++;
            }
            if(nums2[j] > nums1[i])
                i++;
            if(nums2[j] < nums1[i])
                j++;
        }
        
        return res;
    };

Log in to reply
 

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