• 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 |


     1 public class Solution {
     2     public int[][] multiply(int[][] A, int[][] B) {
     3         int mA = A.length, nA = A[0].length, nB = B[0].length;
     4         int[][] result = new int[mA][nB];
     5         
     6         for (int i = 0; i < mA; i++) {
     7             for (int j = 0; j < nA; j++) {
     8                 if (A[i][j] != 0) {
     9                     for (int k = 0; k < nB; k++) {
    10                         if (B[j][k] != 0)
    11                             result[i][k] += A[i][j] * B[j][k];
    12                     }
    13                 }
    14             }
    15         }
    16         return result;
    17     }
    18 }
  • 相关阅读:
    Circular vector
    【杂题】进制转换
    【POJ】3006
    【POJ】1503
    【POJ】2262
    【POJ】1083
    【POJ】2739
    对拍
    【POJ】2159
    【POJ】3299
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6411861.html
Copyright © 2020-2023  润新知