311 parse Matrix Multiplication*** New and MEDIUM

注意是稀疏矩阵!!

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 |

for LOOP ELEMENT IN A AND B

class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int rowA = A.length;
        int colA = A[0].length;
        int rowB = B.length;
        int colB = B[0].length;

        int[][] ans = new int[rowA][colB];
        // cij += a[i][k] * b[k][j];
        for (int i = 0; i < rowA; i++) { 
            for (int k = 0; k < colA; k++) {  // the first two loop : loop over the array A 
                if (A[i][k] != 0) {
                    for (int j = 0; j < colB; j++) {//. the second and third loop over B
                        if (B[k][j] != 0) {
                            ans[i][j] += A[i][k] * B[k][j];
                        }
                    }
                }
            }
        }
        return ans;
    }
}

results matching ""

    No results matching ""