码迷,mamicode.com
首页 > 其他好文 > 详细

facebook 311 Sparse Matrix Multiplication

时间:2017-08-13 14:13:21      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:number   code   logs   result   ace   color   hat   cat   mat   

Given two sparse matrices A and B, return the result of AB.

You may assume that As column number is equal to Bs 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 |

 

public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int m = A.length; 
        int n = A[0].length;
        int bn = B[0].length;
        int[][] C = new int[m][bn];
        
        for (int i=0; i<m; i++) {
            for (int k=0; k<n; k++) {
                if (A[i][k] == 0) continue;
                for (int j=0; j<bn; j++) {
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        return C;
    }
}

  

facebook 311 Sparse Matrix Multiplication

标签:number   code   logs   result   ace   color   hat   cat   mat   

原文地址:http://www.cnblogs.com/apanda009/p/7353216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!