描述
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.)
给定一个数组,将数组中每一个数换成除了它以外其他所有数的乘积,要求时间复杂度 O(n) 且不能使用除法。
分析1
要求不能使用除法,只能用乘法,一个可行的方法就是将该位置上左边所有数的乘积,乘上右边所有数的乘积。因此我们可以构造两个数组 fwd[n] 以及 bwd[n] ,其中 fwd[i] 表示 nums[i] 左边所有数的乘积, bwd[i] 表示 nums[i] 右边所有数的乘积。递推公式是:
代码1
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> fwd(n, 1), bwd(n, 1), res(n);
for (int i = 0; i < n - 1; ++i) {
fwd[i + 1] = fwd[i] * nums[i];
}
for (int i = n - 1; i > 0; --i) {
bwd[i - 1] = bwd[i] * nums[i];
}
for (int i = 0; i < n; ++i) {
res[i] = fwd[i] * bwd[i];
}
return res;
}
};
分析2
下面的做法跟上面的做法在思路上是一样的,不过空间复杂度得到了减小。
代码2
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res(nums.size(),1);
int left = 1, right = 1;
for (int i = 0; i < nums.size(); i++) {
res[i] *= left;
left *= nums[i];
}
for (int i = nums.size() - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
};