week11
题目
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].
原题地址:https://leetcode.com/problems/product-of-array-except-self/description/
解析
题意要求给定数组,求出每个元素除该元素外其他所有元素的积,但要求不使用除法且算法的时间复杂度为O(n)
下面介绍的是空间复杂度为O(n)的解法
用长度为数组长度length的vector数组存放中间计算结果及最终结果
遍历一边原数组,当遍历到第i个元素时,begin存放的是前i个元素(不包括第i个元素)的乘积,end存放的是后i个元素(不包括倒数第i个元素)的乘积,则遍历到第length-i-1的时候,end存放的是第i个元素后面所有元素的乘积,将前者的begin和后者的end相乘得到除第i个元素外其他所有元素的乘积
代码
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int length = nums.size();
int begin = 1;
int end = 1;
vector<int> result(length, 1);
for (int i = 0; i < length; ++i) {
result[i] *= begin;
begin *= nums[i];
result[length - i - 1] *= end;
end *= nums[length - i - 1];
}
return result;
}
};