|
| 1 | +<p>Given two sparse vectors, compute their dot product.</p> |
| 2 | + |
| 3 | +<p>Implement class <code>SparseVector</code>:</p> |
| 4 | + |
| 5 | +<ul data-indent="0" data-stringify-type="unordered-list"> |
| 6 | + <li><code>SparseVector(nums)</code> Initializes the object with the vector <code>nums</code></li> |
| 7 | + <li><code>dotProduct(vec)</code> Compute the dot product between the instance of <em>SparseVector</em> and <code>vec</code></li> |
| 8 | +</ul> |
| 9 | + |
| 10 | +<p>A <strong>sparse vector</strong> is a vector that has mostly zero values, you should store the sparse vector <strong>efficiently </strong>and compute the dot product between two <em>SparseVector</em>.</p> |
| 11 | + |
| 12 | +<p><strong>Follow up: </strong>What if only one of the vectors is sparse?</p> |
| 13 | + |
| 14 | +<p> </p> |
| 15 | +<p><strong class="example">Example 1:</strong></p> |
| 16 | + |
| 17 | +<pre> |
| 18 | +<strong>Input:</strong> nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] |
| 19 | +<strong>Output:</strong> 8 |
| 20 | +<strong>Explanation:</strong> v1 = SparseVector(nums1) , v2 = SparseVector(nums2) |
| 21 | +v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8 |
| 22 | +</pre> |
| 23 | + |
| 24 | +<p><strong class="example">Example 2:</strong></p> |
| 25 | + |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] |
| 28 | +<strong>Output:</strong> 0 |
| 29 | +<strong>Explanation:</strong> v1 = SparseVector(nums1) , v2 = SparseVector(nums2) |
| 30 | +v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p><strong class="example">Example 3:</strong></p> |
| 34 | + |
| 35 | +<pre> |
| 36 | +<strong>Input:</strong> nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] |
| 37 | +<strong>Output:</strong> 6 |
| 38 | +</pre> |
| 39 | + |
| 40 | +<p> </p> |
| 41 | +<p><strong>Constraints:</strong></p> |
| 42 | + |
| 43 | +<ul> |
| 44 | + <li><code>n == nums1.length == nums2.length</code></li> |
| 45 | + <li><code>1 <= n <= 10^5</code></li> |
| 46 | + <li><code>0 <= nums1[i], nums2[i] <= 100</code></li> |
| 47 | +</ul> |
0 commit comments