Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2b7e5b3

Browse files
Sparse Matrix Multiplication
1 parent 77213a6 commit 2b7e5b3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎0311_sparseMatrixMultiplication.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[][]} a Sparse matrix.
3+
* @param {number[][]} b Sparse matrix.
4+
* @return {number[]} Indices of two numbers from 'nums' that add up to 'target'
5+
* @summary Sparse Matrix Multiplication {@link https://leetcode.com/problems/sparse-matrix-multiplication/}
6+
* @description Given two sparse matrices, return their multiplication.
7+
* Space O(n*m) - rows of a and cols of b.
8+
* Time O(n^3) - with optimization for skipping zeros should skip most of the iteration.
9+
*/
10+
const multiply = (a, b) => {
11+
const rows = a.length;
12+
const columns = b[0].length;
13+
14+
const c = Array(rows);
15+
for (let index = 0; index < rows; index++) c[index] = Array(columns).fill(0);
16+
17+
for (let i = 0; i < a.length; i++) {
18+
for (let j = 0; j < a[i].length; j++) {
19+
if (a[i][j] === 0) continue;
20+
21+
for (let k = 0; k < b[0].length; k++) {
22+
if (b[j][k] === 0) continue;
23+
c[i][k] += a[i][j] * b[j][k];
24+
}
25+
}
26+
}
27+
28+
return c;
29+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /