LeetCode-Sparse Matrix Multiplication

LiBlog發表於2016-09-02

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:
public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int rowsA = A.length;
        int rowsB = B.length;
        if (rowsA==0 || rowsB==0 || B[0].length==0) return new int[0][0];
        int colsB = B[0].length;
        int colsA = rowsB;
        
        int[][] res = new int[rowsA][colsB];
        for (int i=0;i<rowsA;i++)
            for (int j=0;j<colsA;j++)
                if (A[i][j]!=0){
                    for (int k=0;k<colsB;k++)
                        if (B[j][k]!=0){
                            res[i][k] += A[i][j] * B[j][k];
                        }
                }
                
        return res;
    }
}

 

相關文章