Java O(n) solution, no extra space with explanation


  • 2
    L

    Because we cannot use division, so assume we have two integer arrays with the same length of nums, int[] leftProd = new int[nums.length]; int[] rightProd = new int[nums.length], we store the product of all the left elements in leftProd and the product of all the right elements in rightProd, then the product of leftProd[i] and rightProd[i] will be the value we want to put into the result.

    Take the example of num[] = {2, 4, 3, 6}, then leftProd will be {1, 2, 8, 24} , and rightProd will be {72, 18, 6, 1}.

    public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if(nums == null)    
            return null;
        int[] res = new int[nums.length];
        for(int i = 0; i < nums.length; i++){
            if(i == 0)
                res[i] = 1;
            else
                res[i] = res[i - 1] * nums[i - 1];
        }
        int prod = 1;
        for(int i = nums.length - 1; i >= 0; i--){
            res[i] = res[i] * prod;
            prod *= nums[i];
        }
        return res;
    }
    

    }


  • 0
    Y
    This post is deleted!

  • 0

    "no extra space"? I see i and prod.


Log in to reply
 

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