[LC] 654. Sparse Matrix Multiplication

Given two Sparse Matrix A and B, return the result of AB.

You may assume that A's column number is equal to B's row number.

Example

Example1

Input: 
[[1,0,0],[-1,0,3]]
[[7,0,0],[0,0,0],[0,0,1]]
Output:
[[7,0,0],[-7,0,3]]
Explanation:
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 |

Example2

Input:
[[1,0],[0,1]]
[[0,1],[1,0]]
Output:
[[0,1],[1,0]]

Solution 1:
public class Solution {
    /**
     * @param A: a sparse matrix
     * @param B: a sparse matrix
     * @return: the result of A * B
     */
    public int[][] multiply(int[][] A, int[][] B) {
        // write your code here
        int aRow = A.length;
        int aCol = A[0].length;
        int bCol = B[0].length;
        int[][] res = new int[aRow][bCol];
        for (int i = 0; i < aRow; i++) {
            for (int j = 0; j < aCol; j++) {
                if (A[i][j] != 0) {
                    for (int k = 0; k < bCol; k++) {
                        res[i][k] += A[i][j] * B[j][k];
                    }
                }
            }
        }
        return res;
    }
}

 

Solution 2:

 

posted @ 2020-03-16 22:20  xuan_abc  阅读(123)  评论(0)    收藏  举报