Leetcode 311. Sparse Matrix Multiplication

Description:

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 |

Thinking:

The Brute force method is the most obvious way to solve the problem. But we should notice that it is a sparse matrix. So we don't need so much computation.

Complexity:

The time complexity is O(nmk).

Step:

  1. Find the A[i][k] != 0.
  2. Then find the B[k][j] != 0.
  3. Compute matrix[i][j] += A[i][k]*B[k][j].

    Code:

    public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
    
        int[][] matrix = new int[A.length][B[0].length];
    
        for(int i = 0; i < A.length; i++){
              for(int k = 0; k < A[0].length; k++){
                  if(A[i][k] != 0){
                      for(int j = 0; j < B[0].length; j++){
                          if(B[k][j] != 0){
                              matrix[i][j] += A[i][k]*B[k][j];
                          }
                      }
                  }
              }
        }
        return matrix;
    }
    }
    

    Brute force:

    public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        if(A == null || B == null || A.length == 0 || B.length == 0 || A[0].length == 0 || B[0].length == 0) return null;
        int[][] matrix = new int[A.length][B[0].length];
        for(int i = 0; i < matrix.length; i++){
            for(int k = 0; k < A[0].length; k++){
                for(int j = 0; j < matrix[0].length; j++){
                    matrix[i][j] += A[i][k]*B[k][j];
                }
            }
        }
        return matrix;
    }
    }
    

    Conclusion:

    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.

results matching ""

    No results matching ""