238. Product of Array Except Self

来源:互联网 发布:微机原理接口编程题 编辑:程序博客网 时间:2024/06/06 20:26
问题:

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

分析:从前向后遍历,依次计算每个值,记录左边部分的乘积,可以降低算法复杂度

代码:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int length = nums.size();
        vector<int> nums1;
        int left = 1;//记录左边已经计算过的部分的乘积
        int right = 1;
        for(int i = 0;i < length;i++){
            for(int j = i+1;j < length;j++){//计算右边部分的乘积
                right = nums[j] * right;
            }
            right = left *right;
            nums1.push_back(right);
            right = 1;
            left = left * nums[i];
        }
        return nums1;
    }
};

原创粉丝点击