1570. Dot Product of Two Sparse Vectors (Medium) - TengnanYao/daily_leetcode GitHub Wiki
class SparseVector:
def __init__(self, nums: List[int]):
self.nums = {i: num for i, num in enumerate(nums) if num != 0}
# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: 'SparseVector') -> int:
result = 0
for k in vec.nums.keys():
if k in self.nums:
result += self.nums[k] * vec.nums[k]
return result
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)