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.)
Runtime: 64ms
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 vector<int> result(nums.size(), 1); 5 6 for(int i = 1; i < nums.size(); i++) 7 result[i] = nums[i - 1] * result[i - 1]; 8 9 int right = 1; 10 for(int i = nums.size() - 2; i >= 0; i--){ 11 right *= nums[i + 1]; 12 result[i] = right * result[i]; 13 } 14 15 return result; 16 } 17 };