除自身以外数组的乘积

题目

#238 Product of Array Except Self

给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

示例:
输入: [1,2,3,4]
输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶:你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

解题思路

这道题的要求可以说是很严苛的了,不能使用除法,还要满足O(n)的时间复杂度和O(1)的空间复杂度。

为了完成这样的要求,只能使用累乘法,为了不包含自身,只能错位累乘,如下例所示:

1
2
3
4
原始数列:      a      b      c      d      e
从左累乘: 1 a ab abc abcd
从右累乘: bcde cde de e 1
最终结果: bcde acde abde abce abcd

代码

1
2
3
4
5
6
7
8
9
10
11
vector<int> productExceptSelf(vector<int>& nums) {
int len = nums.size();
vector<int> res(len, 1);
for (int i = 0, left = 1, right = 1; i < len; i++) {
res[i] *= left;
res[len-i-1] *= right;
left *= nums[i];
right *= nums[len-i-1];
}
return res;
}