题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
暴力破解法:
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
int[][] A = new int[x][y];
int[][] B = new int[y][z];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
A[i][j] = in.nextInt();
}
}
for (int i = 0; i < y; i++) {
for (int j = 0; j < z; j++) {
B[i][j] = in.nextInt();
}
}
int[][] C = new int[x][z];
for (int i = 0; i < x; i++) {
for (int j = 0; j < z; j++) {
for (int k = 0; k < y; k++) {
C[i][j] += A[i][k] * B[k][j];
}
if (j == z - 1) {
System.out.println(C[i][j]);
} else {
System.out.print(C[i][j] + " ");
}
}
}
}
}
}
使用BufferedReader来输入可以减少运行时间:
import java.util.Scanner;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
//Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
// 注意 hasNext 和 hasNextLine 的区别
//while (in.hasNextInt()) { // 注意 while 处理多个 case
while ((str = br.readLine()) != null) {
// int x = in.nextInt();
// int y = in.nextInt();
// int z = in.nextInt();
int x = Integer.parseInt(str);
int y = Integer.parseInt(br.readLine());
int z = Integer.parseInt(br.readLine());
int[][] A = new int[x][y];
int[][] B = new int[y][z];
// for (int i = 0; i < x; i++) {
// for (int j = 0; j < y; j++) {
// A[i][j] = in.nextInt();
// }
// }
for (int i = 0; i < x; i++) {
String[] params = br.readLine().split(" ");
for (int j = 0; j < y; j++) {
A[i][j] = Integer.parseInt(params[j]);
}
}
// for (int i = 0; i < y; i++) {
// for (int j = 0; j < z; j++) {
// B[i][j] = in.nextInt();
// }
// }
for (int i = 0; i < y; i++) {
String[] params = br.readLine().split(" ");
for (int j = 0; j < z; j++) {
B[i][j] = Integer.parseInt(params[j]);
}
}
int[][] C = new int[x][z];
for (int i = 0; i < x; i++) {
for (int j = 0; j < z; j++) {
for (int k = 0; k < y; k++) {
C[i][j] += A[i][k] * B[k][j];
}
if (j == z - 1) {
System.out.println(C[i][j]);
} else {
System.out.print(C[i][j] + " ");
}
}
}
}
}
}
复杂度分析:
时间复杂度:O(n*m*k),n为A矩阵行数,m为B矩阵列数,k为B矩阵(A矩阵列数)行数
空间复杂度:O(1), 直接判断,无额外空间。


