标签:lin public pre nal interview you visio ... pts
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 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 }
[leetcode] Product of Array Except Self
标签:lin public pre nal interview you visio ... pts
原文地址:https://www.cnblogs.com/boris1221/p/9750017.html