We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent df42490 commit b978647Copy full SHA for b978647
1570-dot-product-of-two-sparse-vectors.js
@@ -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