[leetcode] 238. Product of Array Except Self

来源:互联网 发布:猪八戒淘宝刷销量 编辑:程序博客网 时间:2024/04/28 09:31

Question:

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.)

Solution:

这个题要求用O(n)时间跑出来,而且不可以用除法(否则直接扫一遍算总的积,再扫一遍对每一个除以本身就得到结果)。后续Follow up要求用除返回的数组外O(1)的空间复杂度解题。
一开始想的思路就是扫描两遍,第一遍从前往后,得到一个数组A,使得A[i]为nums[i]前面全部的乘积(A[0]=1);第二遍从后往前,得到一个数组B,使得B[i]为nums[i]后面全部的乘积(B[nums.size()-1]=1)。最后只需A[i]*B[i]就可以得到结果。
但是要使用除返回的数组外O(1)的空间复杂度解题,让我想到,对于B数组,可以在得到B数组的每个元素的过程中直接与在A数组对应元素相乘,最后得到的A数组就是结果。
时间复杂度:O(n)
空间复杂度:O(n)(除去返回的数组为O(1))

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        vector<int> ret;        int now = 1;        for (int i = 0; i < nums.size(); i++) {            ret.push_back(now);            now *= nums[i];        }        now = 1;        for (int i = nums.size()-1; i >= 0; i--) {            ret[i] *= now;            now *= nums[i];        }        return ret;    }};