• 稀疏矩阵乘法 · Sparse Matrix Multiplication


    [抄题]:

    给定两个 稀疏矩阵 A 和 B,返回AB的结果。
    您可以假设A的列数等于B的行数。

     [暴力解法]:

    时间分析:

    空间分析:

    [思维问题]:

    [一句话思路]:

    如果为零则不相乘,优化常数的复杂度。

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 是ans[i][j] 元素变化来进行具体的加减操作,而不是无参数的ans[][] 用来声明,搞混了

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    int[][] ans = new int[m][n]二元数组要给引用分配空间

    [复杂度]:Time complexity: O(n^3-n^2*c) Space complexity: O(m*n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    public class Solution {
        /**
         * @param A: a sparse matrix
         * @param B: a sparse matrix
         * @return: the result of A * B
         */
        public int[][] multiply(int[][] A, int[][] B) {
            int m = A.length;
            int n = B[0].length;
            int[][] ans = new int[m][n];
            //corner case
            if (A == null || A[0] == null || B == null || B[0] == null) {
                return ans;
            }
            //loop
            for (int i = 0; i < A.length; i++) {
                for (int k = 0; k < B.length; k++) {
                    if (A[i][k] == 0) {
                        continue;
                    }
                    for (int j = 0; j < B[0].length; j++) {
                        ans[i][j] += A[i][k] * B[k][j];//
                    }
                }
            }
            return ans;
        }
    }
    View Code
  • 相关阅读:
    Kafka 探险
    Semaphore 源码分析
    ReentrantLock 与 AQS 源码分析
    synchronized 原理分析
    ConcurrentHashMap 源码分析
    LinkedHashMap 源码分析
    HashMap 源码分析
    ArrayList 源码分析
    TCP 详解
    proxifier配合ss,实现全局代理
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8460299.html
Copyright © 2020-2023  润新知