标签:
Taking advantage of ‘sparse‘
class Solution { public: vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) { vector<vector<int>> ret; int ha = A.size(); if(!ha) return ret; int wa = A[0].size(); if(!wa) return ret; int hb = wa; int wb = B[0].size(); if(!wb) return ret; // Preprocessing unordered_map<int, bool> ArowZero, BcolZero; for(int i = 0; i < ha; i ++) { bool bAllZero = true; for(int j = 0; j < wa; j ++) { if(A[i][j]) { bAllZero = false; break; } } ArowZero[i] = bAllZero; } for(int i = 0; i < wb; i ++) { bool bAllZero = true; for(int j = 0; j < hb; j ++) { if(B[j][i]) { bAllZero = false; break; } } BcolZero[i] = bAllZero; } ret.assign(ha, vector<int>(wb, 0)); for(int i = 0; i < ha; i ++) for(int j = 0; j < wb; j ++) { if(!ArowZero[i] && !BcolZero[j]) { int sum = 0; for(int k = 0; k < wa; k ++) { sum += A[i][k] * B[k][j]; } ret[i][j] = sum; } } return ret; } };
LeetCode "Sparse Matrix Multiplication"
标签:
原文地址:http://www.cnblogs.com/tonix/p/5006202.html