[Leetcode]238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

思路:不能用除法,只能用乘法。对于每个位置,最后的结果是他左边的所有数的积乘上右边所有数的积,

比如,对于 3 这个数, 他这个位置上最后的结果为 8 。8 是左边 [ 1, 2 ] 和 右边 [ 3 ] 的乘积。那么我们可

以先反向遍历数组,得到每个位置上相对应的右边的乘积。先初始化一个结果数组[ 1, 1, 1, 1 ]。执行一次

的结果为 [ 24, 12, 4, 1],再正向遍历一次,得到最后的结果为 [24,12,8,6].

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        for (int i = 0; i < n; i++)
            res[i] = 1;
        
        int product = 1;
        for (int i = 0; i < n; i++){
            res[i] *= product;
            product *= nums[i];
        }

        product = 1;
        for (int i = n-1; i>=0; i--){
            res[i] *= product;
            product *= nums[i];
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/David-Lin/p/7911228.html