Leetcode 238 level 2

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


Note:

Actually not a difficult one, but it is quite tricky.

The main thought is to have two variables. For the i-th item, the result of it is just the product of two variables. One is the product of the all the numbers behind the i-th item and another is the product of all the numbers behind the i-th item.


Answer:

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

猜你喜欢

转载自blog.csdn.net/shit_kingz/article/details/79994829