311.稀疏矩阵的乘法Java版

1.直接相乘
三重循环直接全部乘即可,这种方法很简单,不再赘述

2.找出非0的元素进行相乘
题目描述:
给你两个 稀疏矩阵 A 和 B,请你返回 AB 的结果。你可以默认 A 的列数等于 B 的行数。
请仔细阅读下面的示例。
示例:
输入:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]

]
在这里插入图片描述
代码:

int[][] multiply(List<List<Integer>> A, List<List<Integer>> B) {
        List<List<Integer>>tempA=new ArrayList<>();
        List<List<Integer>>tempB=new ArrayList<>();
        List<List<Integer>>ans=new ArrayList<>();
        int[][]array=new int[A.size()][B.get(0).size()];
        for (int j = 0; j < A.size(); j++) {
            tempA.add(new ArrayList<>());
        }
        for(int i=0;i<A.size();i++)
        {
            for (int j = 0; j < A.get(i).size(); j++) {
                if(A.get(i).get(j)!=0){
                    tempA.get(i).add(j);
                }
            }
        }
        for (int j = 0; j < B.get(0).size(); j++) {
            tempB.add(new ArrayList<>());
        }
        for(int i=0;i<B.get(0).size();i++)
        {
            for (int j = 0; j < B.size(); j++) {
                if(A.get(j).get(i)!=0){
                    tempB.get(i).add(j);
                }
            }
        }
        for (int i = 0; i < tempA.size(); i++) {
            for (int j = 0; j < tempB.size(); j++) {
                //使用非零元素较少的数组来实现乘法
                if(tempA.get(i).size()<tempB.get(j).size())
for(int numA:tempA.get(i))
{
    array[i][j]=A.get(i).get(numA)*tempB.get(numA).get(j);
}
else{
                    for(int numB:tempB.get(i))
                    {
                        array[i][j]=A.get(i).get(numB)*tempB.get(numB).get(j);
                    }
                }
            }
        }
        return array;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值