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.)
1 public class Solution { 2 public int[] ProductExceptSelf(int[] nums) { 3 int len = nums.Length; 4 int[] result = new int[len]; 5 6 int left = 1; 7 for (int i = 0; i < len; i++) 8 { 9 result[i] = i == 0 ? left : nums[i - 1] * left; 10 left = result[i]; 11 } 12 13 int right = 1; 14 for (int i = len - 1; i >= 0; i--) 15 { 16 result[i] = right * result[i]; 17 right *= nums[i]; 18 } 19 20 return result; 21 } 22 }