238. Product of Array Except Self
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.)
使得数组上的每一位数变为其他所有数的乘积
C++:
1 class Solution { 2 public: 3 vector<int> multiply(const vector<int>& A) { 4 int len = A.size() ; 5 if (len == 0) 6 return vector<int>() ; 7 vector<int> B(len,1) ; 8 int left = 1 ; 9 for(int i = 0 ; i < len ; i++){ 10 B[i] *= left ; 11 left *= A[i] ; 12 } 13 int right = 1 ; 14 for(int i = len-1 ; i >= 0 ; i--){ 15 B[i] *= right ; 16 right *= A[i] ; 17 } 18 return B ; 19 } 20 };
C++(89ms):
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 int len = nums.size() ; 5 int left = 1 ; 6 int right = 1 ; 7 vector<int> res(len,1) ; 8 for(int i = 0 ; i < len ; i++){ 9 res[i] *= left ; 10 left *= nums[i] ; 11 12 res[len-i-1] *= right ; 13 right *= nums[len-i-1] ; 14 } 15 return res ; 16 } 17 };