1570. Dot Product of Two Sparse Vectors
Tags:
Medium
Skills:
Array
Type:
Free
June 24, 2025
04:33 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Approach
SparseVector với constructor nhận vào mảng số nguyên.{index: value}.dotProduct nhận vào một đối tượng SparseVector khác, duyệt qua vector có ít phần tử khác 0 hơn, kiểm tra nếu chỉ số đó cũng tồn tại ở vector còn lại thì nhân và cộng vào tổng.Solution
1class SparseVector {
2 map: Map<number, number>;
3 constructor(nums: number[]) {
4 this.map = new Map();
5 nums.forEach((val, idx) => {
6 if(val !== 0) this.map.set(idx, val)
7 })
8 }
9
10 // Return the dotProduct of two sparse vectors
11 dotProduct(vec: SparseVector): number {
12 const [smaller, larger] = this.map.size < vec.map.size ? [this.map, vec] : [vec, this.map];
13 let res = 0;
14 for(const [idx, val] of smaller.entries()) {
15 res += val * (larger.get(idX) ?? 0);
16 }
17 return res;
18 }
19}
20
21/**
22 * Your SparseVector object will be instantiated and called as such:
23 * var v1 = new SparseVector(nums1)
24 * var v2 = new SparseVector(nums1)
25 * var ans = v1.dotProduct(v2)
26 */