File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments