311. Sparse Matrix Multiplication

  • Difficulty: Medium

  • Topics: Hash Table

  • Similar Questions:

Problem:

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 |

Solutions:

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        int m = A.size();
        if (m == 0) return {};
        int k = A[0].size();
        if (k == 0) return {};
        int n = B[0].size();
        if (n == 0) return {};

        vector<vector<int>> matrix(m, vector<int>(n, 0));

        for (int row = 0; row < m; ++row) {
            for (int col = 0; col < k; ++col) {
                if (A[row][col] == 0)   continue;
                for (int i = 0; i < n; ++i) {
                    matrix[row][i] += A[row][col] * B[col][i];
                }
            }
        }

        return matrix;
    }
};

results matching ""

    No results matching ""