311. Sparse Matrix Multiplication

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 |

Solution

用行乘行来完成矩阵乘法,这样可以提高cache的命中率

Complexity

O(ABC) O(AC)

Code

class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int a = A.length, b = A[0].length, c = B[0].length;
        int[][] C = new int[A.length][B[0].length];
        for(int i = 0; i < a; i++){
            for(int j = 0; j < b; j++){
                if(A[i][j] != 0){
                    for(int k = 0; k < c; k++)
                        C[i][k] += A[i][j] * B[j][k];
                }
            }
        }
        return C;
    }
}