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;
}