# [LeetCode]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].

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.)


/*---------------------------------------
*   日期：2015-07-31
*   作者：SJF0115
*   题目: 238.Product of Array Except Self
*   网址：https://leetcode.com/problems/product-of-array-except-self/
*   结果：AC
*   来源：LeetCode
*   博客：
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
vector<int> result(size,0);
vector<int> left(size,0);
vector<int> right(size,0);
int leftNum = 1,rightNum = 1;
// left[i] 为 nums[0]...nums[i-1]的连续乘积
// right[i] 为 nums[i+1]...nums[size-1]的连续乘积
for(int i = 0;i < size;++i){
left[i] = leftNum;
right[size-i-1] = rightNum;
leftNum *= nums[i];
rightNum *= nums[size-i-1];
}//for
// 计算不包括自己的所有乘积
for(int i = 0;i < size;++i){
result[i] = left[i] * right[i];
}//for
return result;
}
};

int main(){
Solution s;
vector<int> vec = {1,2};
vector<int> result = s.productExceptSelf(vec);
int size = result.size();
for(int i = 0;i < size;++i){
cout<<result[i]<<" ";
}//for
return 0;
}


<script type="text/javascript"> $(function () {$('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var$numbering = $('<ul/>').addClass('pre-numbering').hide();$(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) {$numbering.append($('<li/>').text(i)); };$numbering.fadeIn(1700); }); }); </script>