Problem:
Given an array of n integers where n > 1, nums
and return an array output
such that's equal to output[i]
th E 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 solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)
Subscribe to see which companies asked this question
1 classSolution {2 Public:3vector<int> productexceptself (vector<int>&nums) {4 5 /*6 idea: Left[i] represents the product of the number before I7 Right[i] Represents the product of the number after I8 then total[i] = Left[i]*right[i]9 sweep the surface two times array resultsTen */ One Avector<int> Left (nums.size (),1); - - for(intI=1; I<nums.size (); i++) the { -left[i]=left[i-1]*nums[i-1]; - } - + intright=1; - + for(intI=nums.size ()-2; i>=0; i--) A { atright=nums[i+1]*Right ; -left[i]*=Right ; - } - - returnLeft ; - in - } to};
Leetcode:product of Array Except self