238. Product of Array Except Self

来源:互联网 发布:网络借贷管理办法 编辑:程序博客网 时间:2024/06/11 18:08

题目

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)时间内, 求出数组每一个除了nums[i]以外其他所有数的乘积.

分析

将i位置上的乘积分成两部分:左边的[0: i-1]和右边的[i+1:n-1]
从左到右对每个i而言,左边部分乘积是可以累积上来的.
同理从右到左也是这样.
所以两轮循环, 先从左到右算出每个i左边所有数的乘积, 再从右到左算出每个i右边所有数的乘积

实现

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        vector<int> res(nums.size());        res[0] = 1;        for (int i = 1; i < nums.size(); i++)            res[i] = res[i-1]*nums[i-1];        int rightCulmProdt = 1;        for (int i = nums.size()-1; i >=0; i--) {            res[i] *= rightCulmProdt;            rightCulmProdt *= nums[i];        }        return res;    }};
原创粉丝点击