1、前言
給定兩個 稀疏矩陣 A 和 B,返回AB的結(jié)果派继。
您可以假設(shè)A的列數(shù)等于B的行數(shù)排监。
輸入:
[[1,0,0],[-1,0,3]]
[[7,0,0],[0,0,0],[0,0,1]]
輸出:
[[7,0,0],[-7,0,3]]
解釋:
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 |
2、思路
按照矩陣的乘法運算來運算玖瘸,最后的結(jié)果是 m * y
3秸讹、代碼
public int[][] multiply(int[][] a, int[][] b) {
int m = a.length, n = a[0].length;
int x = b.length, y = b[0].length;
int[][] res = new int[m][y];
for(int i = 0; i < m; i++){
for(int j = 0; j < y; j++){
int[] aArr = a[i];
int sum = 0;
for (int index = 0; index < aArr.length; index++) {
sum += a[i][index] * b[index][j];
}
res[i][j] = sum;
}
}
return res;
}