This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) { | |
int m = A.size(), n = m ? A[0].size() : 0, k = B.size() ? B[0].size() : 0; | |
vector<vector<int>> res(m, vector<int>(k, 0)); | |
unordered_map<int, unordered_map<int, int>> matrix; | |
for (int i = 0; i < m; ++i) | |
{ | |
for (int j = 0; j < n; ++j) | |
{ | |
if(A[i][j]) | |
matrix[i][j] = A[i][j]; | |
} | |
} | |
for (int i = 0; i < m; ++i) | |
{ | |
for (int j = 0; j < k; ++j) | |
{ | |
auto row = matrix[i]; | |
for (auto&& cell : row) | |
{ | |
int col = cell.first; | |
if (B[col][j])res[i][j] += cell.second * B[col][j]; | |
} | |
} | |
} | |
return res; | |
} | |
}; |
我们还有一种不用额外空间的方法。对于A中的某个元素A[i][j],其只可能分别和B[j][0->k]的乘积累加到C[i][0->k]中,所以我们只需要在遍历A的每个不为0的元素的时候,不断更新C即可。时间复杂度为O(m * d * k),常数空间,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) { | |
int m = A.size(), n = m ? A[0].size() : 0, k = B.size() ? B[0].size() : 0; | |
vector<vector<int>> res(m, vector<int>(k, 0)); | |
for (int i = 0; i < m; ++i) | |
{ | |
for (int j = 0; j < n; ++j) | |
{ | |
if (A[i][j]) | |
{ | |
for (int x = 0; x < k; ++x) | |
if (B[j][x])res[i][x] += A[i][j] * B[j][x]; | |
} | |
} | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment