311. Sparse Matrix Multiplication

Description

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:

example

Solution

HashMap, time O(m * max(n, l)), space O(n * l)

因为给定的matrix是稀疏矩阵,所以我们要做一些对于0的预处理。
由于C[i][k] = A[i][x] * B[x][k], 0 <= x <= n
我们可以用一个HashMap,将B中每行不为0的元素保存下来。
然后遍历A,将每个不为0的元素累加到C中去。

class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        if (A == null || A[0] == null || B == null || B[0] == null) {
            return null;
        }
        
        int m = A.length;
        int n = A[0].length;
        int l = B[0].length;
        int[][] C = new int[m][l];
        
        Map<Integer, Map<Integer, Integer>> tableB = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            tableB.put(i, new HashMap<>());
            
            for (int j = 0; j < l; ++j) {
                if (B[i][j] == 0) {
                    continue;
                }
                tableB.get(i).put(j, B[i][j]);
            }
        }
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (A[i][j] == 0) {
                    continue;
                }
                
                for (Map.Entry<Integer, Integer> entry : tableB.get(j).entrySet()) {
                    C[i][entry.getKey()] += A[i][j] * entry.getValue();
                }
            }
        }
        
        return C;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,187评论 0 2
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • 俗世繁闹,声声似刀似潮 被寂寞侵扰,躁动的心失去喧嚣 醉生梦死之后,眼前是无边的忧愁 悄悄 悄悄 灵魂爬上心梢 ...
    鎏某阅读 2,999评论 0 2
  • 今年夏天很幸运能够在6月20号到8月1日在印尼万隆做项目,我们的项目是Igreen,以提高人们的环保意识为主旨,宣...
    大王自己来巡山阅读 3,382评论 0 0
  • 《聪明女人背小包》——优雅不是奢侈,也绝非廉价,而是适合 选择你最需要的,以优雅的姿态面对生活。 1、如何整理自己...
    我是胡小白阅读 1,099评论 0 1

友情链接更多精彩内容