Leetcode - Sparse Matrix Multiplication

My code:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        if (A == null || B == null || A.length == 0 || A[0].length == 0 || B.length == 0 || B[0].length == 0) {
            return null;
        }
        
        int m = A.length;
        int n = A[0].length;
        int l = B[0].length;
        HashMap<Integer, Map<Integer, Integer>> tableB = new HashMap<Integer, Map<Integer, Integer>>();
        int[][] ret = new int[m][l];
        
        for (int i = 0; i < n; i++) {
            tableB.put(i, new HashMap<Integer, Integer>());
            for (int j = 0; j < l; j++) {
                if (B[i][j] != 0) {
                    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) {
                    Map<Integer, Integer> map = tableB.get(j);
                    for (Integer k : map.keySet()) {
                        ret[i][k] += A[i][j] * map.get(k);
                    }
                }
            }
        }
        
        return ret;
    }
}

reference:
https://discuss.leetcode.com/topic/30626/java-and-python-solutions-with-and-without-tables

看了答案写出来的。
本来的时间复杂度是, O(m * n * n * l)
现在的时间复杂度是, O(m * n + n * l) 考虑到稀疏矩阵

用一个 HashMap 保存下, B 中,每一行非0得元素,已经他们的列号。

遍历 A, 每到 (i, j)
就去 B中, 找出, 第 j 行,所有的非零元素 (HashMap 即可做到。),比如, B[j][k]
然后累加到 c[i][k] 上。

差不多就这样了。

Anyway, Good luck, Richardo! -- 09/22/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 一年级语文上册生字表 生字表一(共400字) 啊(ā)爱(ài)安(ān)岸(àn)爸(bà)八(bā)巴(bā)...
    meychang阅读 8,124评论 0 6
  • sì 支zhī茶chá 对duì 酒jiǔ,赋fù 对duì 诗shī,燕yàn子zi 对duì 莺yīng 儿é...
    每个人的孟母堂阅读 5,054评论 0 6
  • 尽管妮可是妹妹,她却一直担心伊斯梅。妮可认为,她姐姐在怎么安排自己的生活方面没有多少经验。伊斯梅选择上一所大学,是...
    道无显隐阅读 2,299评论 0 0
  • 最近在读李笑来的《把时间当作朋友》,都到《现实》一章,文中说: 尽管现实总是如此难于接受,坚强的你却应该坦然。以上...
    邱小猫阅读 2,939评论 1 0

友情链接更多精彩内容