1570. Dot Product of Two Sparse Vectors
Problem description:
Given two sparse vectors, compute their dot product.
Implement class SparseVector
:
SparseVector(nums)
Initializes the object with the vectornums
dotProduct(vec)
Compute the dot product between the instance of SparseVector andvec
A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector.
Follow up: What if only one of the vectors is sparse?
Example 1:
1 | Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] |
Example 2:
1 | Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] |
Example 3:
1 | Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] |
Constraints:
n == nums1.length == nums2.length
1 <= n <= 10^5
0 <= nums1[i], nums2[i] <= 100
Solution:
Since the vector is sparse, we only store indices with values that are nonzero.
A trick in dotProduct
is to use the more sparse array as base to do less calculation.
1 | class SparseVector: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: