classSparseVector:def__init__(self,nums:List[int]):self.d={i:vfori,vinenumerate(nums)ifv}# Return the dotProduct of two sparse vectorsdefdotProduct(self,vec:"SparseVector")->int:a,b=self.d,vec.diflen(b)<len(a):a,b=b,areturnsum(v*b.get(i,0)fori,vina.items())# Your SparseVector object will be instantiated and called as such:# v1 = SparseVector(nums1)# v2 = SparseVector(nums2)# ans = v1.dotProduct(v2)
classSparseVector{publicMap<Integer,Integer>d=newHashMap<>(128);SparseVector(int[]nums){for(inti=0;i<nums.length;++i){if(nums[i]!=0){d.put(i,nums[i]);}}}// Return the dotProduct of two sparse vectorspublicintdotProduct(SparseVectorvec){vara=d;varb=vec.d;if(b.size()<a.size()){vart=a;a=b;b=t;}intans=0;for(vare:a.entrySet()){inti=e.getKey(),v=e.getValue();ans+=v*b.getOrDefault(i,0);}returnans;}}// 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);
classSparseVector{public:unordered_map<int,int>d;SparseVector(vector<int>&nums){for(inti=0;i<nums.size();++i){if(nums[i]){d[i]=nums[i];}}}// Return the dotProduct of two sparse vectorsintdotProduct(SparseVector&vec){autoa=d;autob=vec.d;if(a.size()>b.size()){swap(a,b);}intans=0;for(auto&[i,v]:a){if(b.count(i)){ans+=v*b[i];}}returnans;}};// Your SparseVector object will be instantiated and called as such:// SparseVector v1(nums1);// SparseVector v2(nums2);// int ans = v1.dotProduct(v2);
typeSparseVectorstruct{dmap[int]int}funcConstructor(nums[]int)SparseVector{d:=map[int]int{}fori,x:=rangenums{ifx!=0{d[i]=x}}returnSparseVector{d}}// Return the dotProduct of two sparse vectorsfunc(this*SparseVector)dotProduct(vecSparseVector)(ansint){a,b:=this.d,vec.diflen(a)>len(b){a,b=b,a}fori,x:=rangea{ify,has:=b[i];has{ans+=x*y}}return}/** * Your SparseVector object will be instantiated and called as such: * v1 := Constructor(nums1); * v2 := Constructor(nums2); * ans := v1.dotProduct(v2); */
classSparseVector{d:Map<number,number>;constructor(nums:number[]){this.d=newMap();for(leti=0;i<nums.length;++i){if(nums[i]!=0){this.d.set(i,nums[i]);}}}// Return the dotProduct of two sparse vectorsdotProduct(vec:SparseVector):number{leta=this.d;letb=vec.d;if(a.size>b.size){[a,b]=[b,a];}letans=0;for(const[i,x]ofa){if(b.has(i)){ans+=x*b.get(i)!;}}returnans;}}/** * Your SparseVector object will be instantiated and called as such: * var v1 = new SparseVector(nums1) * var v2 = new SparseVector(nums1) * var ans = v1.dotProduct(v2) */