Given two sparse vectors, compute their dot product.
Implement class SparseVector:
SparseVector(nums) Initializes the object with the vector nums
dotProduct(vec) Compute the dot product between the instance of SparseVector and vec
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?
class SparseVector {
private Map<Integer, Integer> indexToVal = new HashMap<>();
SparseVector(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) continue;
indexToVal.put(i, nums[i]);
}
}
// Return the dotProduct of two sparse vectors
public int dotProduct(SparseVector vec) {
if (vec.getValueSize() < indexToVal.size()) {
return vec.dotProduct(this);
}
Map<Integer, Integer> other = vec.getValues();
int sum = 0;
for (int k : indexToVal.keySet()) {
if (other.containsKey(k)) {
sum += indexToVal.get(k) * other.get(k);
}
}
return sum;
}
public Map<Integer, Integer> getValues() {
return indexToVal;
}
public int getValueSize() {
return indexToVal.size();
}
}
// Your SparseVector object will be instantiated and called as such:
// SparseVector v1 = new SparseVector(nums1);
// SparseVector v2 = new SparseVector(nums2);
// int ans = v1.dotProduct(v2);