zoukankan      html  css  js  c++  java
  • LeetCode 311 稀疏矩阵的乘法

    1. 题目

    给你两个 稀疏矩阵 A 和 B,请你返回 AB 的结果。
    你可以默认 A 的列数等于 B 的行数。

    请仔细阅读下面的示例。

    示例:
    输入:
    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 |

    题解:

    按照两个矩阵相乘的公式计算结果.

    Since It is spase, skip k loop when A[i][j] == 0.

    Time Complexity: O(m*n*o). m = A.length, n = A[0].length, o = B[0].length.

    Space: O(1). regardless res.

    class Solution {
        public int[][] multiply(int[][] A, int[][] B) {
            int m = A.length;
            int n = A[0].length;
            int o = B[0].length;
    
            int [][] res = new int[m][o];
            for(int i = 0; i<m; i++){
                for(int j = 0; j<n; j++){
                    if(A[i][j] != 0){
                        for(int k = 0; k<o; k++){
                            res[i][k] += A[i][j]*B[j][k];
                        }
                    }
                }
            }
            return res;
        }
    }
  • 相关阅读:
    flex
    导航守卫 -vue
    H5 History
    JSX -react
    插槽slot -vue
    js 模拟鼠标绘制方块
    js 模拟滚动条
    js 实现简易留言板功能
    js 实现端口列表话
    js 为数组编写该方法;indexOf
  • 原文地址:https://www.cnblogs.com/kpwong/p/14653151.html
Copyright © 2011-2022 走看看