zoukankan      html  css  js  c++  java
  • LeetCode "Sparse Matrix Multiplication"

    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;
        }
    };
  • 相关阅读:
    JSON
    邮箱正则表达式
    聚聚科技---PHP开发笔试题及答案
    PHP字符串左边补0,字符串右边补0
    CSS3实现带阴影的弹球
    背景颜色渐变
    CSS3---滤镜
    CSS3裁剪与遮罩解析
    CSS3---混合模式
    使用CSS3制作各种形状
  • 原文地址:https://www.cnblogs.com/tonix/p/5006202.html
Copyright © 2011-2022 走看看