首页 > 其他 > 详细

[LC] 654. Sparse Matrix Multiplication

时间:2020-03-16 23:24:07      阅读:75      评论:0      收藏:0      [点我收藏+]

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:

 

[LC] 654. Sparse Matrix Multiplication

原文:https://www.cnblogs.com/xuanlu/p/12507368.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!