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.)
分析:题目翻译一下: 要求计算一个数组中,除了自己本身之外的所有元素的乘积,不能使用除法。
光看要求,不看限制,我们有两个思路:
1、计算所有元素的乘积product,然后从头到尾遍历,对于任意的i,res[i] = product / nums[i]。
这当然是最一般的方法,但是不能用除法,这个方法就忽略了。
2、加入我们计算i位置的结果res[i],实际就是计算res[i]=nums[0]*nums[1]*...*nums[i-1]*nums[i+1]*...*nums[nums.length-1]
下面就是玄学:
res[i]=nums[0]*nums[1]*...*nums[i-1]*nums[i+1]*...*nums[nums.length-1]=(nums[0]*nums[1]*...*nums[i-1])*(nums[i+1]*...*nums[nums.length-1])
也就是将结果分成两个部分,left和right,所以res[i]=left[i]*right[i],下面就是找如何确定left和right数组。
left[i]=nums[0]*nums[1]*...*nums[i-1],这就是一个递归嘛。,left[i]=left[i-1]*nums[i-1]
代码如下:
1 class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 int n = nums.length; 4 5 int[] left = new int[n]; 6 left[0] = 1; 7 for ( int i = 1 ; i < n ; i ++ ) 8 left[i] = left[i-1] * nums[i-1]; 9 10 int[] right = new int[n]; 11 right[n-1] = 1; 12 for ( int i = n-2 ; i >= 0 ; i -- ) 13 right[i] = right[i+1] * nums[i+1]; 14 15 int[] res = new int[n]; 16 for ( int i = 0 ; i < n ; i ++ ) 17 res[i] = left[i] * right[i]; 18 19 return res; 20 } 21 }
运行时间1ms,击败100%。
但是这个方法还是用到了多余的空间,题目说希望可以不使用多余的空间。因此可以用一个right变量来代替从右向左的那次遍历。
参考discuss大神的代码:
1 public int[] productExceptSelf(int[] nums) { 2 int n = nums.length; 3 int[] res = new int[n]; 4 res[0] = 1; 5 for (int i = 1; i < n; i++) { 6 res[i] = res[i - 1] * nums[i - 1]; 7 } 8 int right = 1; 9 for (int i = n - 1; i >= 0; i--) { 10 res[i] *= right; 11 right *= nums[i]; 12 } 13 return res; 14 }