[letecode java] Product of Array Except Self

来源:互联网 发布:java棕色rgb 编辑:程序博客网 时间:2024/06/04 04:52

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


利用一个left数组和right数组,left数组存储第i个数左边所有数的乘积,right存储第i个数右边所有数的乘积,则result[i]=left[i]*right[i]。时间花费为3n,满足o(n)要求,但空间复杂度却不满足要求。所以需要在数组更新上另想办法。而如果在一个数组上更新,result数组中应先存储right数组,用一个变量tmp存储当前的left值即可。代码如下:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] result =new int[nums.length];
        result[nums.length-1]=1;
        int temp=1;
        for(int i=nums.length-2;i>=0;i--)
          result[i]=result[i+1]*nums[i+1];
        for(int i=0;i<nums.length;i++){
            result[i]=temp*result[i];
            temp=temp*nums[i];
        }
        return result;
    }
}

0 0