Skip to content

Commit

Permalink
add 52
Browse files Browse the repository at this point in the history
  • Loading branch information
CaiFengGH authored Apr 19, 2018
1 parent df243bd commit 8239858
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions CodingInterview/52-计算数组元素的乘积.md
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;
}
}
```

0 comments on commit 8239858

Please sign in to comment.