给定两个 稀疏矩阵 :大小为 m x k 的稀疏矩阵 mat1 和大小为 k x n 的稀疏矩阵 mat2 ,返回 mat1 x mat2 的结果。你可以假设乘法总是可能的。
示例 1:
输入:mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
输出:[[7,0,0],[-7,0,3]]
示例 2:
输入:mat1 = [[0]], mat2 = [[0]]
输出:[[0]]
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {int m = mat1.size();int k = mat1[0].size();int n = mat2[0].size();unordered_map<int, list<pair<int, int>>> map1;unordered_map<int, list<pair<int, int>>> map2;for (int i {0}; i < m; i++) {for (int j {0}; j < k; j++) {if (mat1[i][j] != 0) map1[mat1[i][j]].push_back(make_pair(i, j));}} for (int i = 0; i < k; i++) {for (int j = 0; j < n; j++) {if (mat2[i][j] != 0) map2[mat2[i][j]].push_back(make_pair(i, j));}}vector<vector<int>> res(m, vector<int>(n, 0));if (m == 0 || n == 0) return res;for (auto& element1 : map1) {for (auto& list_node1 : element1.second) {for (auto& element2 : map2) {for (auto& list_node2 : element2.second) {if (list_node1.second == list_node2.first) {res[list_node1.first][list_node2.second] += element1.first * element2.first;}}}}}return res;}