238. Product of Array Except Self

    /*
     * 238. Product of Array Except Self
     * 12.7 by Mingyang
     * 先遍历一遍数组,每一个位置上存之前所有数字的乘积。
     * 那么一遍下来,最后一个位置上的数字是之前所有数字之积,是符合题目要求的,
     * 只是前面所有的数还需要在继续乘。我们这时候再从后往前扫描,
     * 每个位置上的数在乘以后面所有数字之积,对于最后一个位置来说,由于后面没有数字了,所以乘以1就行
     * 巧妙的地方:这个题目不需要我们多设置一个array,因为题目的要求是:
     * 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.)
     * 也就是说我们不需要额外的东西,只需要res的array就好了,自己做的时候还要一个left array 还要一个right array
     * 都是可以避免的哈
     */
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        res[0] = 1;
        for (int i = 1; i < n; i++) {
            res[i] = res[i - 1] * nums[i - 1];   //有一点DP的思想在里面
        }
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5597096.html