题目
链接:https://leetcode.com/problems/product-of-array-except-self/
**Level: ** Medium
Discription:
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 1:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note:
-
Please solve it without division and in O(n).
-
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) {
vector<int> ret=nums;
int temp=1;
for(int i=0;i<nums.size();i++)
{
ret[i]=temp;
temp*=nums[i];
}
temp=1;
for(int i=nums.size()-1;i>=0;i--)
{
ret[i]*=temp;
temp*=nums[i];
}
return ret;
}
};
思考
- 算法时间复杂度为O(N),空间复杂度为O(1),不算输出的ret。
- 比较困难的是这题不允许使用除法,使用两次循环,一次记录该数前面的数的乘积,一次记录该数之后的乘积。