[leetcode] 311. Sparse Matrix Multiplication 解题报告

题目链接: https://leetcode.com/problems/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:

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的情况会超时, 因此可以做一个简单的优化, 如果A的某一行全是0的话,则可以不用再计算了.

代码如下:

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        if(A.size() == 0 || B.size() == 0)
            return vector<vector<int>>(0);
        vector<vector<int>> result(A.size(), vector<int>(B[0].size(), 0));
        vector<int> hash1(A.size(), 0), hash2(B[0].size(), 0);
        for(int i = 0; i< A.size(); i++)
            for(int j =0; j< A[0].size(); j++)
            {
                if(A[i][j] != 0)
                {
                    hash1[i] = 1 ;
                    break;
                }
            }
        for(int i = 0; i< B[0].size(); i++)
            for(int j =0; j< B.size(); j++)
            {
                if(B[i][j] != 0)
                {
                    hash2[i] = 1 ;
                    break;
                }
            }
        for(int i =0; i< A.size(); i++)
            for(int j = 0; j< B[0].size(); j++)
                if(hash1[i] != 0 && hash2[j] != 0)
                    for(int k =0; k < A[0].size(); k++)
                        result[i][j] += A[i][k]* B[k][j];
        return result;
    }
};


你可能感兴趣的:(LeetCode,array)