[LeetCode]102. 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.)

 

Subscribe to see which companies asked this question

 
解法1:不考虑常数空间复杂度,设置两个辅助数组,扫描两次数组,分别保存当前值左边所有数的乘积和右边所有数的乘积。最后再循坏一遍,将两个辅助数组对应位置相乘即为输出。
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> leftPro(n, 1), rightPro(n, 1), output(n, 0);
        for (int i = 1; i < n; ++i)
            leftPro[i] = leftPro[i - 1] * nums[i - 1];
        for (int i = n - 2; i >= 0; --i)
            rightPro[i] = rightPro[i + 1] * nums[i + 1];
        for (int i = 0; i < n; ++i)
            output[i] = leftPro[i] * rightPro[i];
        return output;
    }
};

 

解法2:要压缩空间复杂度至常数,而输出数组不计入在内,可以利用输出数组先保存leftPro或者rightPro中的一个,然后再扫描数组,将相应位置乘上rightPro/leftPro即可。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size(), rightPro = 1;
        vector<int> output(n, 1);
        for (int i = 1; i < n; ++i)
            output[i] = output[i - 1] * nums[i - 1];
        for (int i = n - 2; i >= 0; --i) {        
            rightPro *= nums[i + 1];
            output[i] *= rightPro;
        }
        return output;
    }
};

 

posted @ 2015-12-09 09:18  AprilCheny  阅读(168)  评论(0编辑  收藏  举报