forked from CaiFengGH/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
>题目描述 | ||
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…A[i-1]*A[i+1]…*A[n-1]。其中A[i] = 1。不能使用除法; | ||
|
||
- 实现方法 | ||
|
||
避免使用O(n^2)的实现,使用下三角和上三角矩阵的乘积来实现; | ||
|
||
``` | ||
package DayCode; | ||
/** | ||
* @author Ethan | ||
* @desc 计算数组乘积,不使用这种方法的时间复杂度为O(n^2) | ||
* https://blog.csdn.net/rebirth_love/article/details/51612096 | ||
*/ | ||
public class C52Multiply { | ||
public int[] multiply(int[] a){ | ||
//1-异常参数检测 | ||
if(a == null || a.length == 0){ | ||
return null; | ||
} | ||
//2-初始化 d:下三角 c:上三角 b:结果 | ||
int len = a.length; | ||
int[] d = new int[len]; | ||
int[] c = new int[len]; | ||
int[] b = new int[a.length]; | ||
//3-赋值d | ||
d[0] = 1; | ||
for(int i = 1; i < len;i++){ | ||
d[i] = d[i-1] * a[i-1]; | ||
} | ||
//4-赋值c | ||
c[len - 1] = 1; | ||
for(int j = len - 1; j > 0;j--){ | ||
c[j-1] = c[j] * a[j]; | ||
} | ||
//5-计算b | ||
for(int k = 0; k < len; k++){ | ||
b[k] = d[k] * c[k]; | ||
} | ||
return b; | ||
} | ||
} | ||
``` |