This is the solution about Leetcode-String to Integer (atoi).

Description

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 |

Solution

Analysis

Solution1

The basic logic implication of calculation.

Solution2

For Each element with the same row, we multiply each time.
So we can multiply one by one and check if the element is non-zero digit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
public int[][] multiply(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for(int i=0; i<A.length; i++) {
for(int j=0; j<B[0].length; j++) {
int sum = 0;
for(int m = 0; m<B.length; m++) {
if(A[i][m]!=0 && B[m][j]!=0) {
sum += A[i][m] * B[m][j];
}
}
result[i][j] = sum;
}
}
return result;
}
}
public class Solution {
public int[][] multiply(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for(int i=0; i<A.length; i++) {
for(int j=0; j<A[0].length; j++) { //A's column, also B's row
if(A[i][j] != 0) {
for(int m = 0; m<B[0].length; m++) { // B's column
if(B[j][m] != 0) {
result[i][m] += A[i][j] * B[j][m];
}
}
}
}
}
return result;
}
}