Tuesday, October 27, 2020

L 311. Sparse Matrix Multiplication ---------M

 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 |

 

Constraints:

  • 1 <= A.length, B.length <= 100
  • 1 <= A[i].length, B[i].length <= 100
  • -100 <= A[i][j], B[i][j] <= 100


A:

实现题

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




No comments:

Post a Comment