法1:
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
//暴力
int n = A.length;
if(n<=1)
return null;
int[] B = new int[n];
for(int i=0;i<n;i++){
int res = 1;
for(int j=0;j<n;j++){
if(i!=j)
res*=A[j];
}
B[i] = res;
}
return B;
}
}
法2:分别求前缀和后缀
B[i] = A[0]*...*A[i-1]*A[i+1]*...*A[n-1]
=left[i]*right[i]
left[i]=A[0]*...*A[i-1]
right[i]=A[i+1]*...*A[n-1]
left[0] = 1
left[1] = left[0]*A[0]
left[2] = left[1]*A[1]
....
left[i] = left[i-1]*A[i-1]
同理:
right[i] = right[i+1]*A[i+1]
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int n = A.length;
int[] left = new int[n];
int[] right = new int[n];
int[] B = new int[n];
left[0] = 1;
right[n-1] = 1;
for(int i=1;i<n;i++)
left[i] = left[i-1] * A[i-1];
for(int i=n-2;i>=0;i--)
right[i] = right[i+1] * A[i+1];
for(int i=0;i<n;i++)
B[i] = left[i] * right[i];
return B;
}
}
优化法2:
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int n = A.length;
int[] B = new int[n];
B[0] = 1;
for(int i=1;i<n;i++)
B[i] = B[i-1] * A[i-1];
int tmp = 1; //tmp代替right数组
for(int i=n-2;i>=0;i--){
tmp *=A[i+1];
B[i] = B[i]*tmp;
}
return B;
}
}