Advertisement
Guest User

ProductOfArrayExceptSelfSolution

a guest
Nov 22nd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class ProductOfArrayExceptSelf{
  4.     public static int[] productOfArrayExceptSelf(int[] nums){
  5.         int n = nums.length;
  6.        
  7.         if(n<2){
  8.             return new int[] {0};
  9.         }
  10.  
  11.         int[] left = new int[n];
  12.         int[] right = new int[n];
  13.         int[] res = new int[n];
  14.  
  15.         left[0] = 1;
  16.         right[n-1] = 1;
  17.  
  18.         for(int i=1; i<n; i++){
  19.             left[i] = left[i-1]*nums[i-1];
  20.         }
  21.  
  22.         for(int i=n-2; i>-1; i--){
  23.             right[i] = right[i+1]*nums[i+1];
  24.         }
  25.  
  26.         for(int i=0; i<n; i++){
  27.             res[i] = left[i]*right[i];
  28.         }
  29.  
  30.         return res;
  31.  
  32.     }
  33.  
  34.     public static int[] productOfArrayExceptSelfConstantSpace(int[] nums){
  35.         int n = nums.length;
  36.  
  37.         if(n<2){
  38.             return new int[] {0};
  39.         }
  40.  
  41.         int[] res = new int[n];
  42.  
  43.         res[0] = 1;
  44.  
  45.         for(int i=1; i<n; i++){
  46.             res[i] = res[i-1]*nums[i-1];
  47.         }
  48.  
  49.         int right = 1;
  50.  
  51.         for(int i=n-1; i>-1; i--){
  52.             res[i] *= right;
  53.             right *= nums[i];
  54.         }
  55.  
  56.         return res;
  57.  
  58.     }
  59.  
  60.     public static void main(String args[]){
  61.         int[] nums = {1,2,3,4};
  62.         System.out.println(Arrays.toString(productOfArrayExceptSelf(nums)));
  63.         System.out.println(Arrays.toString(productOfArrayExceptSelfConstantSpace(nums)));
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement