JS solution - short


  • 0
    R

    This works for me. Very short but have to modify an array. We can make a copy of the array first, or use an extra map/array.

    /**
     * @param {number[]} nums1
     * @param {number[]} nums2
     * @return {number[]}
     */
    var intersect = function(nums1, nums2) {
        var result = [];
        
        for (let n of nums1) {
            var index = nums2.indexOf(n);
            if ( index !== -1) {
                result.push(n);
                //remove n from num2
                nums2.splice(index, 1);
            }
        }
        return result;
    };
    

Log in to reply
 

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