문제
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:
Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 10 + 03 + 00 + 24 + 3*0 = 8
Example 2:
Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] Output: 0 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 00 + 10 + 00 + 00 + 0*2 = 0
Example 3:
Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] Output: 6
제한조건
n == nums1.length == nums2.length
1 <= n <= 10^5
0 <= nums1[i], nums2[i] <= 100
아이디어
- 둘의
length
가 같음 ->length
가 0 인경우 진행 x - 둘중 하나만 0인 경우 -> continue
풀이
class SparseVector:
def __init__(self, nums: List[int]):
self.vec = nums
# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: 'SparseVector') -> int:
if len(self.vec) == 0:
return 0
ans = 0
for item in zip(self.vec, vec.vec):
if item[0] == 0 or item[1] == 0:
continue
ans += item[0]*item[1]
return ans
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)
후기
이정도는 쉬웠다
#python