311. Sparse-Matrix-Multiplication
difficulty: Medium
section pre{ background-color: #eee; border: 1px solid #ddd; padding:10px; border-radius: 5px; }
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:
Input:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
Output:
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
Constraints:
1 <= A.length, B.length <= 100
1 <= A[i].length, B[i].length <= 100
-100 <= A[i][j], B[i][j] <= 100
Method One
class Solution {
public int[][] multiply(int[][] A, int[][] B) {
// 不停剪枝就好了。其实就是普通乘法多了两个判断, 有0那我整个就不算了。
int mA = A.length;
int nA = A[0].length;
int mA = B.length; // if nA != mA 要报错。
int nB = B[0].length;
int[][] ans = new int[mA][nB];
for(int rowA = 0; rowA < mA; rowA++ ) {
// index 其实就是 colA, 也等于 rowB.
for(int index = 0; index < nA; index++ ) {
if( A[rowA][index] == 0) {
continue;
}
for(int colB = 0; colB < nB; colB++ ) {
if(B[index][colB] == 0) {
continue;
}
int val = A[rowA][index] * B[index][colB];
ans[rowA][colB] += val;
}
}
}
return ans;
}
}
Last updated
Was this helpful?