238.Product of Array Except Self¶
Tags: Medium
Array
Links: https://leetcode.com/problems/product-of-array-except-self/
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = nums.size();
vector<int> res(n, 1);
for (int i = 1; i < n; ++i) {
res[i] = res[i - 1] * nums[i - 1];
}
int tmp = 1;
for (int i = n - 2; i >= 0; --i) {
tmp *= nums[i + 1];
res[i] *= tmp;
}
return res;
}
};
题意是计算数组内所有数字的乘积,但是不包含当前位置的数字。一个想法是使用前缀乘积和后缀乘积,两个数组,也就是维护当前数字的左半部分的连乘结果和右半部分的连乘结果。这样就需要额外数组。
进一步优化,可以直接用结果数组的空间,先遍历一遍计算前缀乘积,然后逆序遍历的时候,用一个临时变量tmp
保存后缀乘积的结果。