[LeetCode] Product of Array Except Self

479 查看

Problem

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.)

Note

建立乘积数组pro,先从前向后遍历nums,令pro[i]等于nums[i]之前所有元素的乘积;再从后向前遍历,令pro[i]再乘以nums[i]之后所有元素的乘积。如此,pro[i]就等于nums[i]之前所有位累乘的积乘以nums[i]之后所有位累乘的积,product of array except self.

Solution


public class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length == 0) return nums;
        int n = nums.length;
        int[] pro = new int[n];
        int left = 1;
        for(int i = 0; i < n; i++){
            pro[i] = left;
            left *= nums[i];
        }
        int right = 1;
        for(int i = n -1; i >= 0; i--){
            pro[i] *= right;
            right *= nums[i];
        }
        return pro;
    }
}