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

Sparse Matrix Multiplication

时间:2016-08-04 06:48:29      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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 |

 1 public class Solution {
 2     public int[][] multiply(int[][] A, int[][] B) {
 3         if (A == null || A[0] == null || B == null || B[0] == null) return null;
 4         int row = A.length, colA = A[0].length, colB = B[0].length;
 5         int[][] C = new int[row][colB];
 6         
 7         //Map<row, Map<col, val>>
 8         Map<Integer, Map<Integer, Integer>> tableB = new HashMap<>();
 9 
10         // For each row in matrix B, if there is a non-zero value, put it in the hashMap.
11         for (int k = 0; k < colA; k++) {
12             tableB.put(k, new HashMap<Integer, Integer>());
13             for (int j = 0; j < colB; j++) {
14                 if (B[k][j] != 0) {
15                     tableB.get(k).put(j, B[k][j]);
16                 }
17             }
18         }
19 
20         for (int i = 0; i < row; i++) {
21             for (int k = 0; k < colA; k++) {
22                 if (A[i][k] != 0) {
23                     for (Integer j : tableB.get(k).keySet()) {
24                         C[i][j] += A[i][k] * tableB.get(k).get(j);
25                     }
26                 }
27             }
28         }
29         return C;
30     }
31 }

 

Sparse Matrix Multiplication

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5735220.html

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