LeetCode-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:

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;
    }
}

 

posted @ 2016-09-02 14:14  LiBlog  阅读(131)  评论(0编辑  收藏  举报