LeetCode 238. Product of Array Except Self (Medium)

来源:互联网 发布:什么数据库管理系统 编辑:程序博客网 时间:2024/06/02 03:16

题目描述:

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

Example:

Given [1,2,3,4], return [24,12,8,6].

题目大意:给出一个数组,为每一个元素算出除了它本身以外其余元素的积。

思路:两次遍历,第一次从左到右算出每个元素左边所有元素的积,第二次从右到左算出结果。
c++代码:

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