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

Leetcode: Sparse Matrix Multiplication

时间:2015-12-31 08:49:47      阅读:160      评论: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 |

70ms solution:

 1 public class Solution {
 2     public int[][] multiply(int[][] A, int[][] B) {
 3         int m = A.length; 
 4         int n = A[0].length;
 5         int bn = B[0].length;
 6         int[][] C = new int[m][bn];
 7         
 8         for (int i=0; i<m; i++) {
 9             for (int k=0; k<n; k++) {
10                 if (A[i][k] == 0) continue;
11                 for (int j=0; j<bn; j++) {
12                     C[i][j] += A[i][k] * B[k][j];
13                 }
14             }
15         }
16         return C;
17     }
18 }

use one HashTable: 160 ms

The idea is derived from a CMU lecture.

A sparse matrix can be represented as a sequence of rows, each of which is a sequence of (column-number, value) pairs of the nonzero values in the row.

 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 m = A.length, n = A[0].length, l = B[0].length;
 5         int[][] C = new int[m][l];
 6         Map<Integer, HashMap<Integer, Integer>> tableB = new HashMap<>();
 7 
 8         for(int k = 0; k < n; k++) {
 9             tableB.put(k, new HashMap<Integer, Integer>());
10             for(int j = 0; j < l; j++) {
11                 if (B[k][j] != 0){
12                     tableB.get(k).put(j, B[k][j]);
13                 }
14             }
15         }
16 
17         for(int i = 0; i < m; i++) {
18             for(int k = 0; k < n; k++) {
19                 if (A[i][k] != 0){
20                     for (Integer j: tableB.get(k).keySet()) {
21                         C[i][j] += A[i][k] * tableB.get(k).get(j);
22                     }
23                 }
24             }
25         }
26         return C;   
27     }
28 }

 

Leetcode: Sparse Matrix Multiplication

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5090563.html

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