题目描述
给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除了 nums[i] 之外其余各元素的乘积 。
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请 不要使用除法,且在 O(n) 时间复杂度内完成此题。
示例 1:
输入: nums = [1,2,3,4]
输出: [24,12,8,6]
示例 2:
输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]
提示:
2<=nums.length<=1052 <= nums.length <= 10^52<=nums.length<=105
−30<=nums[i]<=30-30 <= nums[i] <= 30−30<=nums[i]<=30
输入 保证 数组 answer[i] 在 32 位 整数范围内
思路1
计算左边的前缀和和右边的前缀和,直接相乘即可。
代码1
cpp
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// 初始化前后缀
int n = nums.size();
vector<int>pre(n, 0);
vector<int>suf(n, 0);
pre[0] = 1;
for(int i = 1; i < n; ++i)
{
pre[i] = pre[i - 1] * nums[i - 1];
}
suf.back() = 1;
for(int i = n - 2; i >= 0; --i)
{
suf[i] = suf[i + 1] * nums[i + 1];
}
// 输出答案
vector<int> ans;
for(int i = 0 ; i < n; ++i)
{
ans.push_back(pre[i] * suf[i]);
}
return ans;
}
};
思路2
在思路1的基础上,省略前后缀的空间,直接用ans数组作为前缀,然后倒置计算后缀的同时得出答案。
代码2
cpp
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int>ans(n, 1);
for(int i = 1; i < n; ++i)
{
ans[i] = nums[i - 1] * ans[i - 1];
}
int suf = 1; // 代表后缀
for(int i = n - 1; i >=0; --i)
{
ans[i] = ans[i] * suf;
suf *= nums[i];
}
return ans;
}
};