zoukankan      html  css  js  c++  java
  • [leetcode]311. 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:

    Input:
    
    A = [
      [ 1, 0, 0],
      [-1, 0, 3]
    ]
    
    B = [
      [ 7, 0, 0 ],
      [ 0, 0, 0 ],
      [ 0, 0, 1 ]
    ]
    
    Output:
    
         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                      | 0 0 1 |

    注意:

    搞清楚何谓matrix multiply:

    一定要有A column 等于B row的特性才能进行matrix multiply

         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |   //  1*7 + 0*0 + 0*0 = 7
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                      | 0 0 1 |
         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |   //  1*0 + 0*0 + 0*0 = 0
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                      | 0 0 1 |
         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |  // 1*0 + 0*0 + 0*1 = 0
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                      | 0 0 1 |
         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // -1*7 + 0*0 + 3*0 = -7
                      | 0 0 1 |

    思路:

    Brute Force:  create product 2D matrix, iterate through it and calculate result for each position

    Optimized: Use the information that matrix is sparse. Iterate through A and add the contribution of each number to the result matrix. If A[i][j] == 0, skip the calculation

    代码:

     1 class Solution {
     2     public int[][] multiply(int[][] A, int[][] B) {
     3         int m =  A.length, n = A[0].length;
     4         int nB = B[0].length;
     5         int [][] res = new int[m][nB];
     6         
     7         for(int i = 0; i< m; i++){
     8             for(int k = 0; k < n; k++){
     9                 if(A[i][k]!=0){ // use Sparse Matrix attributes
    10                     for(int j = 0; j < nB; j++){
    11                         if(B[k][j]!=0) res[i][j] += A[i][k] *B[k][j];                    
    12                     }
    13                 }
    14             }
    15         }
    16        return res;  
    17     }  
    18 }
  • 相关阅读:
    如何判断单链表是否存在环
    语法面试等题目汇总
    数据分析师常见的10道面试题解答
    Python 的函数
    Python 的错误和异常处理
    Python 的条件语句和循环语句
    Python 的基本运算和内置函数
    Python 的数据表示
    Python 基础
    关于 Python
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10014531.html
Copyright © 2011-2022 走看看