238. Product of Array Except Self
238. Product of Array Except Self
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.)
My Solutions:
对于某一个数字,如果知道其前面所有数字的乘积,同时也知道后面所有的数乘积,那么二者相乘就是要的结果。所以分别创建出这两个数组,分别从数组的两个方向遍历就可以分别创建出乘积累积数组。
再进行空间上的优化: 由于最终的结果都是要乘到结果res中,所以我们可以不用单独的数组来保存乘积,而是直接累积到res中:
先从左到右遍历一遍,将乘积的结果存入res中。在res里把第一个数记做1。res里其他的数是nums里的数所有左边数的乘积。比如【1,2,3,4】的res会是【1,1,2,6】
然后从右到左开始遍历,用一个临时变量right,初始化为1,当做右边所有数的乘积。每次移动先更新res里的数为最终结果res[i] = res[i] * right,然后更新right: right = right * nums[i]。比如res=【1,1,2,6】
res=【1,1,2,6】,right=4
res=【1,1,8,6】,right=4*3=12
res=【1,12,8,6】, right=12*2=24
res=【24,12,8,6】
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
res[0] = 1;
//save the the left product for nums[i] at res[i]
for (int i = 1; i < nums.length; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
// save the final result in res[i] as res[i] * right; update right to be right * nums[i]
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}
Last updated