leetcode刷题,总结,记录,备忘238

来源:互联网 发布:淘宝发布宝贝怎么预览 编辑:程序博客网 时间:2024/06/06 07:39

leetcode238

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

这题有点惭愧,, 自己没想出来,看了别人的解法,,顿时感觉简单,先从头遍历,将每一个位置上的之前的元素乘积保存在临时的数组中,然后再重尾巴开始倒着遍历数组再承一遍,将每个位置上右边的元素乘积与临时数组中的值相乘得到最终结果。自己在纸上写写画画走走流程就明白了。

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


0 0