Product of Array Except Self

来源:互联网 发布:首份网络主播黑名单 编辑:程序博客网 时间:2024/04/30 09:57

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


以后补充下O(1)空间复杂度的解法。

思路是左边扫一次,右边骚一次,分别把当前数字的左边的乘积结果保存在一个数组,然后右侧扫一遍,保存右侧的乘积结果,然后输出。


代码:

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

再简化一些可以只使用一个变量保存中间结果:


0 0