Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
tag: array
method 1
动态规划,使用两个动态数组。leftDp[i] 表示i左边的数的乘积,rightDp[i] 表示i右边的数的乘积,那么res[i] = leftDp[i] * leftDp[i]
public int[] productExceptSelf1(int[] nums) {
int i, j;
int[] leftDP = new int[nums.length];
int[] rightDP = new int[nums.length];
int leftProduct = 1;
int rightProduct = 1;
leftDP[0] = 1;
rightDP[nums.length-1] = 1;
for (i = 1, j = nums.length-2; i < nums.length; i++,j--) {
leftProduct *= nums[i-1];
rightProduct *= nums[j+1];
leftDP[i] = leftProduct;
rightDP[j] = rightProduct;
}
int[] answer = new int[nums.length];
for (int k = 0; k < nums.length; k++) {
answer[k] = leftDP[k]*rightDP[k];
}
return answer;
}
method 2
观察method 1,其实不算严格意义上的动态规划,method 1使用了两个额外的数组,深入考虑我们发现,其实res[i] 相当于乘了左边的乘积之后乘右边的乘积,method 1是同时乘,这里可以把这两个过程分开,在一次循环中遍历两次
public int[] productExceptSelf2(int[] nums) {
int i, j;
int leftProduct = 1;
int rightProduct = 1;
int[] answer = new int[nums.length];
for (int k = 0; k < answer.length; k++) {
answer[k] = 1;
}
for (i = 1, j = nums.length-2; i < nums.length; i++,j--) {
leftProduct *=nums[i-1];
rightProduct *= nums[j+1];
answer[i] *= leftProduct;
answer[j] *= rightProduct;
}
return answer;
}
method 3
相当于将method 2 中的一个循环拆成两个循环
public int[] productExceptSelf3(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0, tmp = 1; i < nums.length; i++) {
result[i] = tmp;
tmp *= nums[i];
}
for (int i = nums.length - 1, tmp = 1; i >= 0; i--) {
result[i] *= tmp;
tmp *= nums[i];
}
return result;
}
summary:
- 优化时考虑能否将诸如储存累乘结果的数组简化为一个变量
- 一次循环两次遍历