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

    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 |
    
     
     Solution:
    public class Solution {
        public int[][] multiply(int[][] A, int[][] B) {
            int rowsA = A.length;
            int rowsB = B.length;
            if (rowsA==0 || rowsB==0 || B[0].length==0) return new int[0][0];
            int colsB = B[0].length;
            int colsA = rowsB;
            
            int[][] res = new int[rowsA][colsB];
            for (int i=0;i<rowsA;i++)
                for (int j=0;j<colsA;j++)
                    if (A[i][j]!=0){
                        for (int k=0;k<colsB;k++)
                            if (B[j][k]!=0){
                                res[i][k] += A[i][j] * B[j][k];
                            }
                    }
                    
            return res;
        }
    }
  • 相关阅读:
    sqhhb
    12333
    12

    今日份
    12
    彻底理解 Cookie、Session、Token
    https原理
    12312
    uiower
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5833314.html
Copyright © 2011-2022 走看看