modify code

master
algorithmzuo 3 years ago
parent 35153ad3fb
commit cb86646344

@ -57,24 +57,27 @@ public class Code02_FibonacciProblem {
int[][] t = m;// 矩阵1次方 int[][] t = m;// 矩阵1次方
for (; p != 0; p >>= 1) { for (; p != 0; p >>= 1) {
if ((p & 1) != 0) { if ((p & 1) != 0) {
res = muliMatrix(res, t); res = product(res, t);
} }
t = muliMatrix(t, t); t = product(t, t);
} }
return res; return res;
} }
// 两个矩阵乘完之后的结果返回 // 两个矩阵乘完之后的结果返回
public static int[][] muliMatrix(int[][] m1, int[][] m2) { public static int[][] product(int[][] a, int[][] b) {
int[][] res = new int[m1.length][m2[0].length]; int n = a.length;
for (int i = 0; i < m1.length; i++) { int m = b[0].length;
for (int j = 0; j < m2[0].length; j++) { int k = a[0].length; // a的列数同时也是b的行数
for (int k = 0; k < m2.length; k++) { int[][] ans = new int[n][m];
res[i][j] += m1[i][k] * m2[k][j]; for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < m;j++) {
for(int c = 0; c < k; c++) {
ans[i][j] += a[i][c] * b[c][j];
} }
} }
} }
return res; return ans;
} }
public static int s1(int n) { public static int s1(int n) {

@ -78,23 +78,27 @@ public class Code03_ZeroLeftOneStringNumber {
int[][] tmp = m; int[][] tmp = m;
for (; p != 0; p >>= 1) { for (; p != 0; p >>= 1) {
if ((p & 1) != 0) { if ((p & 1) != 0) {
res = muliMatrix(res, tmp); res = product(res, tmp);
} }
tmp = muliMatrix(tmp, tmp); tmp = product(tmp, tmp);
} }
return res; return res;
} }
public static int[][] muliMatrix(int[][] m1, int[][] m2) { // 两个矩阵乘完之后的结果返回
int[][] res = new int[m1.length][m2[0].length]; public static int[][] product(int[][] a, int[][] b) {
for (int i = 0; i < m1.length; i++) { int n = a.length;
for (int j = 0; j < m2[0].length; j++) { int m = b[0].length;
for (int k = 0; k < m2.length; k++) { int k = a[0].length; // a的列数同时也是b的行数
res[i][j] += m1[i][k] * m2[k][j]; int[][] ans = new int[n][m];
for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < m;j++) {
for(int c = 0; c < k; c++) {
ans[i][j] += a[i][c] * b[c][j];
} }
} }
} }
return res; return ans;
} }
public static void main(String[] args) { public static void main(String[] args) {

Loading…
Cancel
Save