311. Sparse Matrix Multiplication (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:

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 1: Brute Force O(m * n * l); O(1)
    public int[][] multiply(int[][] A, int[][] B) {//A: m * n; B: n * l
        int[][] res = new int[A.length][B[0].length]; //m * l
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                for (int k = 0; k < B[0].length; k++) {
                    res[i][k] += A[i][j] * B[j][k];
                }
            }
        }
        return res;
    }
Solution 2: Pruning O(m * n * l); O(1)

那么我们来看结果矩阵中的某个元素C[i][j]是怎么来的,起始是A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... + A[i][k]*B[k][j],那么为了不重复计算0乘0,我们首先遍历A数组,要确保A[i][k]不为0,才继续计算,然后我们遍历B矩阵的第k行,如果B[K][J]不为0,我们累加结果矩阵res[i][j] += A[i][k] * B[k][j]

    /**
     * Matrix multiplication is row in A multiply column in B.
     * When implement, for A[i][j], multiply a row B[j][k], 0 <= k < nB.
     * Then add result to res[i][k].
     * Skip zeros since the matrix is sparse.
     * <p>
     * Loop through A from left to right, row by row.
     * In each row, multiply the column value A[i][j] with each value in row j in B, B[j][k].
     * Add it to res[i][k].
     */
    public int[][] multiply(int[][] A, int[][] B) {
        int mA = A.length, nA = A[0].length;
        int nB = B[0].length;
        int[][] res = new int[mA][nB];

        for (int i = 0; i < mA; i++) {
            for (int j = 0; j < nA; j++) {
                if (A[i][j] == 0) { //res[i][k] += A[i][j] * B[j][k],A[i][j]为0,就没要必要往下计算了。
                    continue; // Skip zeros in A.
                }
                for (int k = 0; k < nB; k++) {
                    if (B[j][k] == 0) {
                        continue; // Skip zeros in B.
                    }
                    res[i][k] += A[i][j] * B[j][k];
                }
            }
        }
        return res;
    }

results matching ""

    No results matching ""