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
| 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 |
|
感觉也没什么意思的题目
Ref: https://discuss.leetcode.com/topic/30625/easiest-java-solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public int[][] multiply(int[][] A, int[][] B) { int m = A.length, n = A[0].length, nB = B[0].length; int[][] C = new int[m][nB]; for (int i = 0; i < m; i++) { for (int k = 0; k < n; k++) { if (A[i][k] != 0) { for (int j = 0; j < nB; j++) { if (B[k][j] != 0) C[i][j] += A[i][k] * B[k][j]; } } } } return C; }
|