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 }
public class Solution {
public int[][] multiply(int[][] A, int[][] B) {
if (A == null || A[] == null || B == null || B[] == null) return null;
int rowA = A.length, colA = A[].length, colB = B[].length;
int[][] C = new int[rowA][colB]; //Map<row, Map<col, val>>
Map<Integer, Map<Integer, Integer>> tableB = new HashMap<>(); // For each row in matrix B, if there is a non-zero value, put it in the hashMap.
for (int row = ; row < colA; row++) {
tableB.put(row, new HashMap<Integer, Integer>());
for (int col = ; col < colB; col++) {
if (B[row][col] != ) {
tableB.get(row).put(col, B[row][col]);
}
}
} for (int row = ; row < rowA; row++) {
for (int col = ; col < colA; col++) {
if (A[row][col] != ) {
for (Integer j : tableB.get(col).keySet()) {
C[row][j] += A[row][col] * tableB.get(col).get(j);
}
}
}
}
return C;
}
}