Sparse Matrix Multiplication

Source

  • leetcode: 311
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.

java

public class Solution {
    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++) {
                        C[i][j] += A[i][k] * B[k][j];
                    }
                }
            }
        }
        return C;   
    }
}



//按照矩阵公式应该是这样的, 但是就不能用if(A[i][k]!=0)来优化了
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 j = 0; j < nB; j++) {
                for(int k = 0; k < n; k++) { 
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        return C;   
 }