zoukankan      html  css  js  c++  java
  • leetcode311- Sparse Matrix Multiplication- medium

    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:

    A = [
      [ 1, 0, 0],
      [-1, 0, 3]
    ]
    
    B = [
      [ 7, 0, 0 ],
      [ 0, 0, 0 ],
      [ 0, 0, 1 ]
    ]
    
    
         |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
    AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                      | 0 0 1 |
    

     1.O(mkn)复杂度。三重for循环直接做。

    2.O(mk + nk)复杂度。Map<Integer, List<Integer>>或者List<List<Integer>>来辅助做。存储B矩阵里面非0数的横纵坐标B[k][j]信息。之后遍历A矩阵,入股遇到非0数A[i][k],用存储的信息做一次for循环。非0数A[i][k]就是最后能做贡献的数,它最后会和所有共享k的B[k][...]的数一起做贡献,具体和B[k][j]数就是贡献到result[i][j]的位置。

     1.O(mkn)复杂度
    class Solution {
        public int[][] multiply(int[][] A, int[][] B) {
            if (A == null || B == null || A.length == 0 || A[0].length == 0 || B[0].length == 0) {
                return new int[0][0];
            }
            int m = A.length;
            int c = A[0].length;
            int n = B[0].length;
            int[][] result = new int[m][n];
            
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int sum = 0;
                    for (int k = 0; k < c; k++) {
                        sum += A[i][k] * B[k][j];
                    }
                    result[i][j] = sum;
                }
            }
            
            return result;
        }
    }

    2.O(mk+nk)复杂度。

    class Solution {
        public int[][] multiply(int[][] A, int[][] B) {
            if (A == null || B == null || A.length == 0 || A[0].length == 0 || B[0].length == 0) {
                return new int[0][0];
            }
            int m = A.length;
            int t = A[0].length;
            int n = B[0].length;
            int[][] result = new int[m][n];
            Map<Integer, List<Integer>> idxB = new HashMap<>();
            
            for (int k = 0; k < t; k++) {
                idxB.put(k, new ArrayList<Integer>());
                for (int j = 0; j < n; j++) {
                    if (B[k][j] != 0) {
                        idxB.get(k).add(j);
                    }
                }
            }
            
            for (int i = 0; i < m; i++) {
                for (int k = 0; k < t; k++) {
                    if (A[i][k] == 0) {
                        continue;
                    }
                    for (int j : idxB.get(k)) {
                        result[i][j] += A[i][k] * B[k][j];
                    }
                }
            }
            
            return result;
        }
    }
  • 相关阅读:
    实现一个基本的静态文件服务的Web服务器
    Http模块
    Java环境
    HelloWorld
    HTTP(s)
    第16条:复合优先于继承
    Tomcat配置https
    第15条:使可变性最小化
    第14条:在公有类中使用访问 方法而非公有域
    第13条:使类和成员的可访问性最小化
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7917458.html
Copyright © 2011-2022 走看看