238. Product of Array Except Self

  • nums[i]的左乘积 = nums[i]左边元素的值 * nums[i]左边元素的左乘积
  • nums[i]的右乘积 = nums[i]右边元素的值 * nums[i]右边元素的右乘积
  • nums[i]的productExceptSelft = nums[i]的左乘积 * nums[i]的右乘积
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        
        int[] leftProduct = new int[n];
        int[] rightProduct = new int[n];
        
        leftProduct[0] = 1;
        for (int i = 1; i < n; i++) {
            leftProduct[i] = nums[i - 1] * leftProduct[i - 1];
        }
        
        rightProduct[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            rightProduct[i] = nums[i + 1] * rightProduct[i + 1];
        }
        
        for (int i = 0; i < n; i++) {
            res[i] = leftProduct[i] * rightProduct[i];
        }
        return res;
    }
}

Reference

https://leetcode-cn.com/problems/product-of-array-except-self/solution/gan-jue-da-bu-fen-ti-jie-du-shi-tie-dai-ma-jia-fu-/