[LC] 238. Product of Array Except Self


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

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

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

class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }
        int[] resArr = new int[nums.length];
        resArr[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            resArr[i] = resArr[i - 1] * nums[i - 1];
        }
        
        int right = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            resArr[i] *= right;
            right *= nums[i];
        }
        return resArr;
    }
}
public class Solution {
    /**
     * @param nums: an array of integers
     * @return: the product of all the elements of nums except nums[i].
     */
    public int[] productExceptSelf(int[] nums) {
        // write your code here
        int len = nums.length;
        int[] prefix = new int[len];
        int[] suffix = new int[len];
        for (int i = 0; i < len; i++) {
            if (i == 0) {
                prefix[i] = nums[i];
                continue;
            }
            prefix[i] = prefix[i - 1] * nums[i];
        }
        for(int i = len - 1; i >= 0; i--) {
            if (i == len - 1) {
                suffix[i] = nums[i];
                continue;
            }
            suffix[i] = suffix[i + 1] * nums[i];
        }
        int[] res = new int[len];
        for (int i = 0; i < len; i++) {
            if (i == 0) {
                res[i] = suffix[i + 1];
                continue;
            }
            if (i == len - 1) {
                res[i] = prefix[i - 1];
                continue;
            }
            res[i] = prefix[i - 1] * suffix[i + 1];
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xuanlu/p/11881034.html