zoukankan      html  css  js  c++  java
  • 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 |
    public class Solution {
        public int[][] multiply(int[][] A, int[][] B) 
        {
            int ma = A.length;
            int na = A[0].length;
            int mb = B.length;   //na = mb
            int nb = B[0].length;
            
            int[][] C = new int[ma][nb];
            for(int i=0; i<ma;i++)
            {
                for(int k=0; k<na;k++)
                {
                   if (A[i][k] != 0) 
                   {
                        for (int j = 0; j < nb; j++) 
                        {
                            if (B[k][j] != 0) C[i][j] += A[i][k] * B[k][j];
                        }
                    }
                    
                }
                
            }
            return C;
        }
    }

    reference: https://leetcode.com/discuss/71912/easiest-java-solution

  • 相关阅读:
    [USACO06NOV]Corn Fields(状压DP)
    关灯问题II (状态压缩 BFS)
    天梯---至多删三个字符(DP)
    天梯
    蓝桥
    天梯
    天梯
    天梯
    天梯
    蓝桥
  • 原文地址:https://www.cnblogs.com/hygeia/p/5097708.html
Copyright © 2011-2022 走看看