238. Product of Array Except Self
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)中完成。
可以将每一个从前到后和从后到前的乘数保存下来,例如ret[8]就是0-6的相乘和8-n-1的相乘的相乘。
这里还要是否考虑乘数可能溢出,是否要使用大数的问题,这里先用int试试
- class Solution {
- public:
- vector<int> productExceptSelf(vector<int>& nums) {
- int n = nums.size();
- vector<int> ret(n,1);
- int from_start=1;
- int from_end=1;
- for(int i=0;i<n;i++){
- ret[i]*=from_start;
- from_start*=nums[i];
- ret[n-i-1]*=from_end;
- from_end*=nums[n-i-1];
- }
- return ret;
- }
- };