Topic:
Given sparse matrices A and B, return the result of AB.
You could assume that A's column number is equal to B ' s row number.
Example:
A = [ [1, 0, 0], [-1, 0, 3]]b = [ [7, 0, 0], [0, 0, 0], [0, 0, 1]] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
Links: http://leetcode.com/problems/sparse-matrix-multiplication/
Exercises
Sparse matrix multiplied. The topic hints to use HASHMAP, so we use HashMap, save a in not 0 lines, and b in the column not 0, and then traverse two hashmap to update the result array.
Time Complexity-o (MNKL), Space Complexity-o (MN + KL).
Public classSolution { Public int[] Multiply (int[] A,int[] B) {if(A = =NULL|| B = =NULL|| A.length = = 0 | | B.length = = 0 | | (A[0].length! =b.length)) {return New int[][]{}; } Map<integer,int[]> Rowina =NewHashmap<> ();//store Non-zero rows in AMap<integer,int[]> COLINB =NewHashmap<> ();//store Non-zero cols in B for(inti = 0; i < a.length; i++) { for(intj = 0; J < A[0].length; J + +) { if(a[i][j]! = 0) {rowina.put (I, a[i]); Break; } } } for(intj = 0; J < B[0].length; J + +) { for(inti = 0; i < b.length; i++) { if(b[i][j]! = 0) { int[] tmp =New int[B.length]; for(intk = 0; K < B.length; k++) {Tmp[k]=B[k][j]; } colinb.put (J, TMP); Break; } } } int[] res =New int[A.length] [B[0].length]; for(intI:rowina.keyset ()) { for(intJ:colinb.keyset ()) { for(intk = 0; K < A[0].length; k++) {Res[i][j]+ = Rowina.get (i) [K] *Colinb.get (j) [K]; } } } returnRes; }}
Reference:
311.Sparse Matrix Multiplication