题目描述
给你一个整数数组 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]
个人C++解答
如果这道题可以允许使用除法的话就会变得更简单,计算出所有的乘积后除以当前位置就好(有0单独考虑),不允许使用除法的话,为保证O(n)的时间复杂度,可以采用左右分别乘的思路,先将该数左边的数全部乘后保存,再乘右边的数
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> answer(nums.size(),1);
int index_ = 1, temp = 0;
for (int i = 0;index_ < nums.size();i++,index_++) {
temp = answer[i];
answer[index_] = answer[index_] * nums[i] * temp;
}
index_ = nums.size() - 2;
temp = 1;
for (int i = nums.size() - 1; index_ >= 0;i--,index_--) {
temp = temp* nums[i];
answer[index_] = answer[index_] * temp;
}
return answer;
}
};