1570. Dot product of sparse vectors

Suppose we have very large sparse vectors (most of the elements in vector are zeros) 

  1. Find a data structure to store them
  2. Compute the Dot Product.

Follow-up:
What if one of the vectors is very small? (binary search)

 1 a = [(1,2),(2,3),(100,5)]
 2 b = [(0,5),(1,1),(100,6)]
 3 
 4 i = 0; j = 0
 5 result = 0
 6 while i < len(a) and j < len(b):
 7     if a[i][0] == b[j][0]:
 8         result += a[i][1] * b[j][1]
 9         i += 1
10         j += 1
11     elif a[i][0] < b[j][0]:
12         i += 1
13     else:
14         j += 1
15 print(result)

 

 1 class SparseVector {
 2     Map<Integer, Integer> indexMap = new HashMap<>();
 3 
 4     SparseVector(int[] nums) {
 5         for (int i = 0; i < nums.length; i++)
 6             if (nums[i] != 0)
 7                 indexMap.put(i, nums[i]);
 8     }
 9 
10     public int dotProduct(SparseVector vec) {
11         if (indexMap.size() == 0 || vec.indexMap.size() == 0) {
12             return 0;
13         }
14             
15         if (indexMap.size() > vec.indexMap.size()) {
16             return vec.dotProduct(this);
17         }
18             
19         int productSum = 0;
20         for (Map.Entry<Integer, Integer> entry : indexMap.entrySet()) {
21             int index = entry.getKey();
22             Integer vecValue = vec.indexMap.get(index);
23             if (vecValue != null) {
24                 productSum += (entry.getValue() * vecValue);
25             }
26         }
27         return productSum;
28     }
29 }

 

posted @ 2020-02-06 11:33  北叶青藤  阅读(301)  评论(0编辑  收藏  举报