238. Product of Array Except Self

来源:互联网 发布:java获取当前文件路径 编辑:程序博客网 时间:2024/04/27 23: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).

For example, given [1,2,3,4], return [24,12,8,6].

solution:

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        vector<int> res;        int c = 1;        for(int i=0; i<nums.size(); i++){            res.push_back(c);            c *= nums[i];        }        c = 1;        for(int i=nums.size()-1; i>=0; i--){            res[i] *= c;            c *= nums[i];        }        return res;    }};
心得:思路比较清晰,顺序逆序各乘一次;

运行速度:快

0 0