Skip to content

Commit b978647

Browse files
authored
Create 1570-dot-product-of-two-sparse-vectors.js
1 parent df42490 commit b978647

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {SparseVector}
4+
*/
5+
const SparseVector = function(nums) {
6+
this.seen = {}
7+
nums.forEach((e, i) => {
8+
if(e !== 0) this.seen[i] = e
9+
})
10+
};
11+
12+
// Return the dotProduct of two sparse vectors
13+
/**
14+
* @param {SparseVector} vec
15+
* @return {number}
16+
*/
17+
SparseVector.prototype.dotProduct = function(vec) {
18+
let res = 0
19+
for(let [k, v] of Object.entries(vec.seen)) {
20+
if(k in this.seen) res += v * this.seen[k]
21+
}
22+
return res
23+
};
24+
25+
// Your SparseVector object will be instantiated and called as such:
26+
// let v1 = new SparseVector(nums1);
27+
// let v2 = new SparseVector(nums2);
28+
// let ans = v1.dotProduct(v2);

0 commit comments

Comments
 (0)