File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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);
You can’t perform that action at this time.
0 commit comments