• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Sparse Matrix Multiplication

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 }

 

posted @ 2015-12-31 07:57  neverlandly  阅读(2547)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3