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).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
//不让我们用除法。如果让用除法的话,那这道题就应该属于Easy,因为可以先遍历一遍数组求出所有数字之积,然后除以对应位置的上的数字。但是这道题禁止我们使用除法,那么我们只能另辟蹊径。我们想,对于某一个数字,如果我们知道其前面所有数字的乘积,同时也知道后面所有的数乘积,那么二者相乘就是我们要的结果,所以我们只要分别创建出这两个数组即可,分别从数组的两个方向遍历就可以分别创建出乘积累积数组
// Given numbers [2, 3, 4, 5], regarding the third number 4, the product of array except 4 is 2*3*5 which consists of two parts: left 2*3 and right 5. The product is left*right. We can get lefts and rights:
// Numbers: 2 3 4 5
// Lefts: 2 2*3 2*3*4
// Rights: 3*4*5 4*5 5
// Let’s fill the empty with 1:
// Numbers: 2 3 4 5
// Lefts: 1 2 2*3 2*3*4
// Rights: 3*4*5 4*5 5 1
// We can calculate lefts and rights in 2 loops. The time complexity is O(n).
// We store lefts in result array. If we allocate a new array for rights. The space complexity is O(n). To make it O(1), we just need to store it in a variable which is right in @lycjava3’s code.
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
// Calculate lefts and store in res.
int left = 1;
for (int i = 0; i < n; i++) {
if (i > 0)
left = left * nums[i - 1];
res[i] = left;
}
// Calculate rights and the product from the end of the array.
int right = 1;
for (int i = n - 1; i >= 0; i--) {
if (i < n - 1)
right = right * nums[i + 1];
res[i] *= right;
}
return res;
}