Sparse Matrix Multiplication

Given twosparse matrices A and B, return the result of AB.

You may assume that A's column number is equal to B's row number.

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 |

题意:实现稀疏矩阵相乘,稀疏矩阵的特点是矩阵中绝大多数的元素为0,而相乘的结果是还应该是稀疏矩阵,即还是大多数元素为0,那么我们使用传统的矩阵相乘的算法肯定会处理大量的0乘0的无用功,所以我们需要适当的优化算法

图解

分析

代码

class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int m =  A.length, n = A[0].length; 
        int nB = B[0].length;     
        int [][] res = new int[m][nB]; 

        for(int i = 0; i < m; i++){ 
            for(int k = 0; k < n; k++){
                if(A[i][k]!=0){
                    for(int j = 0; j<nB; j++){
                        if(B[k][j]!=0) res[i][j] += A[i][k] *B[k][j];                    
                    }
                }
            }
        }
       return res;  
    }

}

results matching ""

    No results matching ""