(medium)LeetCode 238.Product of Array Except Self

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

解法:output[p]=pre[p]*after[p]

代码如下:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int len=nums.length;
        int[] output=new int[len];
        int[] pre=new int[len];
        int[]after=new int[len];
        for(int i=0;i<len;i++)
            pre[i]=1;
        for(int j=0;j<len;j++)
            after[j]=1;
        for(int m=1;m<len;m++){
           pre[m]=pre[m-1]*nums[m-1];
        }
        for(int n=len-2;n>=0;n--){
            after[n]=after[n+1]*nums[n+1];
        }
        for(int p=0;p<len;p++){
            output[p]=pre[p]*after[p];
        }
        return output;
    }
}

  运行结果:时间复杂度O(n)

     

原文地址:https://www.cnblogs.com/mlz-2019/p/4702847.html