构建乘积数组_JAVA_简单
构建乘积数组
http://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46
- 目标数组的i对应元素是原数组不包括i元素的乘积,即B[i] = (A[0]*...*A[i-1]) * (A[i+1]*...*A[n-1]),即左侧乘以右侧
- 可以用一次正循环计算左侧乘积,再来一次逆循环计算右侧乘积的同时计算B[i]
public class Solution { public int[] multiply(int[] A) { int[] B = new int[A.length]; // 计算i左侧乘积存入B B[0] = 1; for(int i = 1; i < A.length; i++) { B[i] = A[i - 1] * B[i - 1]; } // 累积i右侧乘积乘以左侧乘积 int right = 1; for(int i = A.length - 1; i >= 0; i--) { B[i] = B[i] * right; right *= A[i]; } return B; } }