Product of Array Except Self

 

CREATED TIME: Feb 04, 2020 11:07 PM UPDATED TIME: Feb 06, 2020 5:15 PM 난이도: Medium

class Solution { public: vector productExceptSelf(vector& nums) { vector left(nums.size()); vector right(nums.size()); vector res(nums.size());

        left[0] = nums[0];
        right[nums.size() - 1] = nums[nums.size() - 1];
        
        for(int i=1; i<nums.size(); i++){
            left[i] = left[i-1] * nums[i];
            right[nums.size() - 1 - i] = right[nums.size() - 1 - i + 1] * nums[nums.size() - 1 - i];
        }
        
        for(int i=0; i<nums.size(); i++){
            int left_product = 1;
            int right_product = 1;
            
            if(i != 0){
                left_product = left[i - 1];
            }
            
            
            if(i != nums.size() - 1){
                right_product = right[i + 1];
            }
            
            res[i] = left_product * right_product;
        }
        return res;
    }
};