Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
public class S238 { public int[] productExceptSelf(int[] nums) { //左右两个数组分别表示nums[i]左右两边的乘积,那么rets[i]=left[i]*right[i] //判断是否为零反而时间变长,本来想法是判断到零就可以结束循环(零以后的数除自己以外的乘积都为零),减少复杂度 /* int []left = new int[nums.length]; left[0] = 1; int []right = new int[nums.length]; right[nums.length-1] = 1; int []rets = new int[nums.length]; for(int i = 1;i<nums.length;i++){ left[i] = left[i-1]*nums[i-1]; right[nums.length-i-1] = right[nums.length-i]*nums[nums.length-i]; if(i>nums.length/2-1){ rets[i] = left[i]*right[i]; } if(nums[i] == 0){ break; } } for(int i = 0;i<nums.length/2;i++){ rets[i] = left[i]*right[i]; if(nums[i] == 0){ break; } } return rets;*/ //减小空间复杂度的方法,同时也降低了运行时间,是否判断零没有影响 int []rets = new int[nums.length]; rets[nums.length-1] = 1; //先求出每个数右侧乘积 for(int i = nums.length-2;i>=0;i--){ rets[i] = rets[i+1]*nums[i+1]; if(nums[i] == 0){ break; } } //再从左往右,求左侧积的时候用rets保存结果 int left = 1; for(int i = 0;i<nums.length;i++){ rets[i] *= left; left *= nums[i]; } return rets; } }