Java Two time scan solution


  • 10
    1. First round:
      scan from left to right to compute the product of all elements to the left of i
      starting value is 1
    2. Second round:
      scan from right to left to compute the product of all elements to the right of i
      use the left product to time the right product

     public int[] productExceptSelf(int[] nums) {
            int[] p = new int[nums.length];
            
            int product = 1;
            for(int i=0;i<p.length;++i){
                p[i] = product;
                product *= nums[i];
            }
            
            product = 1;
            for(int i=p.length-1;i>=0;--i){
                p[i]*=product;
                product*=nums[i];
            }
            return p;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.