2ms Java solution with one loop


  • 4
        public int[] productExceptSelf(int[] nums) {
            int n =nums.length;
            int[] result = new int[n];
            int left = 1, right = 1;
            /*Temp vars would initialize elements in two-loop case; 
            Otherwise, the result array needs to be initialized to 1s in one-loop case.*/
            for (int i = 0; i < n ; i++){
                result[i] = 1;
            }
            /*Two temp vars are needed in one-loop case, 'cause the intermediate results of two reverse scans should be separate; 
             One or no temp for two-loop scenario. */
    
            for (int i = 0; i < n ; i++) {
                result[i] *= left;
                left *= nums[i];
                result[n - i - 1] *= right;
                right *= nums[n - i - 1];
            }
            return result;
        }
    

  • 0
    S

    @Heronalps I can see 2 loops over N! Your title is at least misleading!


Log in to reply
 

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