311. Sparse Matrix Multiplication
Given two sparse matrices A and B, return the result of AB.
You may 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 |
本题是稀疏矩阵,稀疏矩阵的特点是有很多0,因此不能用传统的计算方法来进行运算,这样会TLE,假设通式是这样的C[i][j] += A[i][k]*B[k][j];(不会解释。。。。。)代码如下:
1 public class Solution { 2 public int[][] multiply(int[][] A, int[][] B) { 3 int row = A.length; 4 int col = B[0].length; 5 int z = A[0].length; 6 int[][] C = new int[row][col]; 7 for(int i=0;i<row;i++){ 8 for(int k=0;k<z;k++){ 9 if(A[i][k]!=0){ 10 for(int j=0;j<col;j++){ 11 if(B[k][j]!=0) C[i][j]+=A[i][k]*B[k][j]; 12 } 13 } 14 } 15 } 16 return C; 17 } 18 }