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 |

解题思路:

由于是稀疏矩阵,说明矩阵中存在大量的0,那么对0进行运算实际上是浪费了我们的时间。

我们可以对第一个矩阵进行预处理:

  提取出不为0的下标,存储在二维数组中NoneZero[i][j], i代表行数,NoneZero[i][j] 代表不为0的数组,j并无确切含义

之后我们进行矩阵乘法:用A的行去乘B的列,若A的行NoneZero[i]的大小为0,说明这一行中没有不为0的数字,可以直接跳过。

若不为0,我们可以直接从B中根据NoneZero存储的下标提取数值:

for(int i = 0; i < A.size(); i++){
            if(noneZero[i].size() == 0)  //该行中的数字都为0
                continue;  //所以跳过
            for(int j = 0; j < B[0].size(); j++){    //存在不为0的数字
                for(int n : noneZero[i]){ //由于存储的是下标,我们可以直接提取下标。
                    ret[i][j] += A[i][n]*B[n][j]; } } }

代码:

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<vector<int>> noneZero;
        for(int i = 0; i < A.size(); i++ ){
            vector<int> row;
            for(int j = 0; j < A[0].size(); j++){
                if(A[i][j] != 0)
                    row.push_back(j);
            }
            noneZero.push_back(row);
        }
        vector<vector<int>> ret(A.size(), vector<int>(B[0].size(),0));
        for(int i = 0; i < A.size(); i++){
            if(noneZero[i].size() == 0)
                continue;
            for(int j = 0; j < B[0].size(); j++){
                for(int n : noneZero[i]){
                    ret[i][j] += A[i][n]*B[n][j]; 
                }
            }
        }
        return ret;
    }
    
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9196936.html