Dot Product of Two Sparse Vectors
给一个spare vector的类, 求dot product
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class SparseVector { int[] nums; SparseVector(int[] nums) { this.nums = nums; } // Return the dotProduct of two sparse vectors public int dotProduct(SparseVector vec) { int sum = 0; for(int i = 0; i < nums.length; i++) { sum += nums[i] * vec.nums[i]; } return sum; } } // 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); |