Skip to content

Commit 52dbe6c

Browse files
committed
Add Arrays/1570_Dot_Product_of_Two_Sparse_Vectors.java
1 parent f22090f commit 52dbe6c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class SparseVector {
2+
private Map<Integer, Integer> indexMap;
3+
4+
public SparseVector(int[] nums) {
5+
indexMap = new HashMap<>();
6+
7+
for (int i = 0; i < nums.length; i++) {
8+
if (nums[i] != 0) { indexMap.put(i, nums[i]); }
9+
}
10+
}
11+
12+
// Return the dotProduct of two sparse vectors
13+
public int dotProduct(SparseVector vec) {
14+
int product = 0;
15+
Map<Integer, Integer> vecMap = vec.indexMap;
16+
17+
for (Map.Entry<Integer, Integer> entry : indexMap.entrySet()) {
18+
if (!vecMap.containsKey(entry.getKey())) {
19+
continue;
20+
}
21+
22+
product += entry.getValue() * vecMap.get(entry.getKey());
23+
}
24+
25+
return product;
26+
}
27+
}
28+
29+
// Your SparseVector object will be instantiated and called as such:
30+
// SparseVector v1 = new SparseVector(nums1);
31+
// SparseVector v2 = new SparseVector(nums2);
32+
// int ans = v1.dotProduct(v2);

0 commit comments

Comments
 (0)