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 m = A.length, n = A[0].length, nB = B[0].length;
4 int[][] C = new int[m][nB];
5
6 for (int row = 0; row < m; row++) {
7 for (int col = 0; col < n; col++) {
8 if (A[row][col] != 0) {
9 for (int j = 0; j < nB; j++) {
10 if (B[col][j] != 0) {
11 C[row][j] += A[row][col] * B[col][j];
12 }
13 }
14 }
15 }
16 }
17 return C;
18 }
19 }
1 public class Solution {
2 public int[][] multiply(int[][] A, int[][] B) {
3 if (A == null || A[0] == null || B == null || B[0] == null) return null;
4 int rowA = A.length, colA = A[0].length, colB = B[0].length;
5 int[][] C = new int[rowA][colB];
6
7 //Map<row, Map<col, val>>
8 Map<Integer, Map<Integer, Integer>> tableB = new HashMap<>();
9
10 // For each row in matrix B, if there is a non-zero value, put it in the hashMap.
11 for (int row = 0; row < colA; row++) {
12 tableB.put(row, new HashMap<Integer, Integer>());
13 for (int col = 0; col < colB; col++) {
14 if (B[row][col] != 0) {
15 tableB.get(row).put(col, B[row][col]);
16 }
17 }
18 }
19
20 for (int row = 0; row < rowA; row++) {
21 for (int col = 0; col < colA; col++) {
22 if (A[row][col] != 0) {
23 for (Integer j : tableB.get(col).keySet()) {
24 C[row][j] += A[row][col] * tableB.get(col).get(j);
25 }
26 }
27 }
28 }
29 return C;
30 }
31 }