[LeetCode311]Sparse Matrix Multiplication

来源:互联网 发布:威海近年来人口数据 编辑:程序博客网 时间:2024/04/23 15:59
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 |Hide Company Tags LinkedInHide Tags Hash Table

学渣连矩阵乘法都忘记了,折腾了好久才搞懂,然后写了个大脑都不用动的code居然还能过:

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

就是说用A中的每个元素去乘B,如果A[i][j]=0 就没必要算了啊,这样子。。
但是我没看懂(偷懒没仔细看。。。)discuss分享的那个方法。。要再想想!!!

http://www.cs.cmu.edu/~scandal/cacm/node9.html

0 0
原创粉丝点击