[LeetCode311]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 |

Hide Company Tags LinkedIn
Hide 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章