Skip to content

Commit e3bcd24

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

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

1570-dot-product-of-two-sparse-vectors.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,42 @@ SparseVector.prototype.dotProduct = function(vec) {
2626
// let v1 = new SparseVector(nums1);
2727
// let v2 = new SparseVector(nums2);
2828
// let ans = v1.dotProduct(v2);
29+
30+
// another
31+
32+
class SparseVector {
33+
/**
34+
* @param {number[]} nums
35+
* @return {SparseVector}
36+
*/
37+
constructor(nums) {
38+
// Space: O(n)
39+
this.seen = new Map() // index -> value
40+
for (let i = 0; i < nums.length; ++i) {
41+
if (nums[i] !== 0) {
42+
this.seen.set(i, nums[i])
43+
}
44+
}
45+
}
46+
47+
/**
48+
* Return the dotProduct of two sparse vectors
49+
* @param {SparseVector} vec
50+
* @return {number}
51+
*/
52+
dotProduct(vec) {
53+
// Time: O(n)
54+
let sum = 0
55+
for (const [i, val] of vec.seen) {
56+
if (this.seen.has(i)) {
57+
sum += val * this.seen.get(i)
58+
}
59+
}
60+
return sum
61+
}
62+
}
63+
64+
// Your SparseVector object will be instantiated and called as such:
65+
// let v1 = new SparseVector(nums1);
66+
// let v2 = new SparseVector(nums2);
67+
// let ans = v1.dotProduct(v2);

0 commit comments

Comments
 (0)