LeetCode 1570. Dot Product of Two Sparse Vectors

My solution in JavaScript:

/**
 * @param {number[]} nums
 * @return {SparseVector}
 */
var SparseVector = function(nums) {
    const x = new Map()
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] != 0) {
            x.set(i, nums[i])
        }
    }
    this.map = x
    this.length = nums.length
    return this
};


// Return the dotProduct of two sparse vectors
/**
 * @param {SparseVector} vec
 * @return {number}
 */
SparseVector.prototype.dotProduct = function(vec) {
    let ans = 0;

    for (let i = 0; i < vec.length; i++) {
        if (vec.map.has(i) && this.map.has(i)) {
            ans += vec.map.get(i) * this.map.get(i)
        }
    }

    return ans
};

// Your SparseVector object will be instantiated and called as such:
// let v1 = new SparseVector(nums1);
// let v2 = new SparseVector(nums2);
// let ans = v1.dotProduct(v2);

Published on