zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    威尔逊定理 费马小定理 欧拉定理 扩展欧拉定理
    Prufer编码
    [USACO 08MAR]土地购买 Land Acquisition
    [NOIp2004]虫食算
    [POI2000]病毒

    [NOI导刊] [2010] [提高] 淘汰赛制
    开源的基于云开发的通讯录小程序
    党建答题小程序
    抽奖活动小程序按人头开奖技术分析
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5090563.html
Copyright © 2011-2022 走看看