题目:给定一个数组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],不能使用除法
分析:直观的解法是用连乘n-1个数字得到B[i],时间复杂度为O(n^2)。剑指offer上思路为,B可以用一个矩阵来创建,如图,B[i]为矩阵中第i行所有元素的乘积,不妨设C[i]=A[0]*A[1]*...*A[i-1],D[i]=A[i+1]*...*A[n-2]*A[n-1],则C[i]可以用自上而下的顺序计算,D[i]可以用自下而上的顺序计算,时间复杂度为O(n)
public class wr52multiply { public int [] multiply(int []A){ int length=A.length; int []B=new int[length]; if(length!=0){ B[0]=1; // 左半部分 for(int i=1;i<length;i++){ B[i]=B[i-1]*A[i-1]; } // 右半部分 int temp=1; for(int j=length-2;j>=0;j--){ temp=temp*A[j+1]; B[j]=B[j]*temp; } } return B; } }
在牛客上看到同学对代码for循环进行了分析,感觉对理解挺有帮助:设一个长度为5的数组
则第一个for循环
B[0]=1 B[1]=B[0]*A[0]=A[0] B[2]=B[1]*A[1]=A[0]*A[1] B[3]=B[2]*A[2]=A[0]*A[1]*A[2] B[4]=B[3]*A[3]=A[0]*A[1]*A[2]*A[3]
第二个for循环
temp=A[4] B[3]=B[3]*temp=A[0]*A[1]*A[2]*A[4] temp=A[4]*A[3] B[2]=B[2]*temp=A[0]*A[1]*A[3]*A[4] temp=A[4]*A[3]*A[2] B[1]=B[1]*temp=A[0]*A[2]*A[3]*A[4] temp=A[4]*A[3]*A[2]*A[1] B[0]=B[0]*temp=A[4]*A[3]*A[2]*A[1]