Skip to content

Commit 3093f75

Browse files
authored
Create 311-sparse-matrix-multiplication.js
1 parent 24abd6e commit 3093f75

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

311-sparse-matrix-multiplication.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
3+
Given two sparse matrices A and B, return the result of AB.
4+
You may assume that A's column number is equal to B's row number.
5+
6+
Example:
7+
8+
Input:
9+
10+
A = [
11+
[ 1, 0, 0],
12+
[-1, 0, 3]
13+
]
14+
15+
B = [
16+
[ 7, 0, 0 ],
17+
[ 0, 0, 0 ],
18+
[ 0, 0, 1 ]
19+
]
20+
21+
Output:
22+
23+
| 1 0 0 | | 7 0 0 | | 7 0 0 |
24+
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
25+
| 0 0 1 |
26+
27+
*/
28+
29+
/**
30+
* @param {number[][]} A
31+
* @param {number[][]} B
32+
* @return {number[][]}
33+
*/
34+
const multiply = function(A, B) {
35+
const aLen = A.length, bLen = B.length
36+
if(aLen === 0 || bLen === 0) return []
37+
const aCol = A[0].length, bCol = B[0].length
38+
const res = Array.from({ length: aLen }, () => new Array(bCol).fill(0))
39+
for(let i = 0; i < aLen; i++) {
40+
for(let j = 0; j < bCol; j++) {
41+
let tmp = 0
42+
for(let k = 0; k < bLen; k++) {
43+
tmp += A[i][k] * B[k][j]
44+
}
45+
res[i][j] = tmp
46+
}
47+
}
48+
return res
49+
};

0 commit comments

Comments
 (0)