使用哈希表记录每个稀疏向量的下标和值
然后找出哈希表中的公共项相乘即可
时间复杂度O(n)
class SparseVector {
public:
unordered_map<int,int>hash;
SparseVector(vector<int> &nums) {
for(int i=0;i<nums.size();i++)
hash[i]=nums[i];
}
// Return the dotProduct of two sparse vectors
int dotProduct(SparseVector& vec) {
int res=0;
unordered_map<int,int>hash2=vec.hash;
for(auto [c,v]:hash)
{
if(hash2.count(c))
{
res+=v*hash2[c];
}
}
return res;
}
};
// Your SparseVector object will be instantiated and called as such:
// SparseVector v1(nums1);
// SparseVector v2(nums2);
// int ans = v1.dotProduct(v2);