其他分享
首页 > 其他分享> > 311. Sparse Matrix Multiplication

311. Sparse Matrix Multiplication

作者:互联网

My first solution, time complexityO(m*n), where m is the cell number of mat1, and n is the cell number of mat2:

class Solution {
    public int[][] multiply(int[][] mat1, int[][] mat2) {
        if(mat1==null||mat2==null||mat1.length==0||mat2.length==0)
            return null;
        int[][] res = new int[mat1.length][mat2[0].length];
        for(int k=0;k<mat1.length;k++){
            for(int j=0;j<mat2[0].length;j++){
                int sum = 0;
                for(int i=0;i<mat2.length;i++){
                    sum+=mat1[k][i]*mat2[i][j];
                }
                res[k][j]=sum;
            }
        }
        return res;
    }
}

 My second solution, beat 100%

class Solution {
    public int[][] multiply(int[][] mat1, int[][] mat2) {
        if(mat1==null||mat2==null||mat1.length==0||mat2.length==0)
            return null;
        int[][] res = new int[mat1.length][mat2[0].length];
        for(int i=0;i<mat1.length;i++){
            for(int j=0;j<mat1[0].length;j++){
                if(mat1[i][j]!=0){
                    for(int k=0;k<mat2[0].length;k++){
                        res[i][k]+= mat1[i][j]*mat2[j][k];
                    }
                }
            }
        }
        return res;
    }
}

 

标签:mat2,Matrix,mat1,int,311,number,length,Multiplication,null
来源: https://www.cnblogs.com/feiflytech/p/16163669.html