Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SparseVector:
- def __init__(self, nums: List[int]):
- self.hashmap = {}
- for ind, num in enumerate(nums):
- self.hashmap[ind] = num
- # Return the dotProduct of two sparse vectors
- def dotProduct(self, vec: 'SparseVector') -> int:
- keys1 = list(self.hashmap.keys())
- keys2 = list(vec.hashmap.keys())
- values1 = list(self.hashmap.values())
- values2 = list(vec.hashmap.values())
- result = 0
- i, j = 0, 0
- while(i < len(keys1) and j < len(keys2)):
- if keys1[i] < keys2[j]:
- i += 1
- elif keys1[i] > keys2[j]:
- j += 1
- else:
- result += values1[i] * values2[j]
- i += 1
- j += 1
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement