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 |


 1 public class Solution {
 2     public int[][] multiply(int[][] A, int[][] B) {
 3         int mA = A.length, nA = A[0].length, nB = B[0].length;
 4         int[][] result = new int[mA][nB];
 5         
 6         for (int i = 0; i < mA; i++) {
 7             for (int j = 0; j < nA; j++) {
 8                 if (A[i][j] != 0) {
 9                     for (int k = 0; k < nB; k++) {
10                         if (B[j][k] != 0)
11                             result[i][k] += A[i][j] * B[j][k];
12                     }
13                 }
14             }
15         }
16         return result;
17     }
18 }
原文地址:https://www.cnblogs.com/amazingzoe/p/6411861.html