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

对于一个n>1的数组,输出这样的一个数组:output[i]等于nums中除nums[i]以外所有数的乘积。

Solve it without division and in O(n).

不能使用除法,时间复杂度为O(n).

For example, given [1,2,3,4], return [24,12,8,6].

遍历数组两遍,符合时间复杂度O(n),没有使用额外的空间(额外空间指除了ret之外的空间)。第一遍计算第i个数的左边部分的乘积,第二遍计算第i个数右边部分的乘积。

 1 class Solution {
 2 public:
 3     vector<int> productExceptSelf(vector<int>& nums) {
 4         if(nums.empty())return vector<int>();
 5         int n=nums.size();
 6         vector<int> ret(n,1);
 7         for(int i=1;i<n;i++){
 8             ret[i]=ret[i-1]*nums[i-1];
 9         }
10         int right=1;
11         for(int i=n-1;i>=0;i--){
12             ret[i]*=right;
13             right*=nums[i];
14         }
15         return ret;
16     }
17 };
原文地址:https://www.cnblogs.com/Z-Sky/p/5647697.html