首页 > 代码库 > 238. Product of Array Except Self

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(1),时间复杂度为O(n)。

  1. 细细思量,可以充分利用原序列nums和输出序列output的空间,使得output[i] = nums[0]....nums[i-1],nums[i] = nums[i+1]...nums[n-1],最终,output[i] *= nums[i];这种方法有一个缺陷,需要修改原序列nums,经过查阅答案,作出如下改进;
  2. 保持第一步中output[i] = nums[0]...nums[i-1],但是不再修改原序列,而是改为增加一个临时变量post_product,对序列从后向前遍历,post_product = nums[n-1]...nums[i+1],所以output[i] *= post_product。此时空间复杂度为O(n),时间复杂度为O(1)。
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            if (n <= 1)
                return nums;
                
            vector<int> res(n);
            
            res[0] = 1;
            for (int i = 1; i <= n - 1; ++i)
                res[i] = res[i - 1] * nums[i - 1];
                
            int post_product = 1;
            for (int i = n-2; i >= 0; --i) {
                // 注意起始位置
                post_product *= nums[i+1];
                res[i]  *= post_product;
            }
            return res;
        }
    };

     

238. Product of Array Except Self