sak1b

https://leetcode.com/problems/product-of-array-except-self/

Dec 8th, 2020
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> productExceptSelf(vector<int>& nums) {
  4.         int n=nums.size();
  5.         vector<int> res(n,0);
  6.         vector<int> left;
  7.         vector<int> right(n,0);
  8.        
  9.         left.push_back(nums[0]);
  10.         for(int i=1;i<n;i++)
  11.         {
  12.             left.push_back(nums[i]*left[i-1]);
  13.         }
  14.        
  15.         right[n-1]=nums[n-1];
  16.         for(int i=n-2;i>=0;i--)
  17.         {
  18.             right[i]=(nums[i]*right[i+1]);
  19.         }
  20.        
  21.         res[0]=right[1];
  22.         res[n-1]=left[n-2];
  23.        
  24.         for(int i=1;i<n-1;i++)
  25.         {
  26.             res[i]=left[i-1]*right[i+1];
  27.         }
  28.        
  29.         return res;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment