导航

(medium)LeetCode 238.Product of Array Except Self

Posted on 2015-08-04 18:49  骄阳照林  阅读(169)  评论(0编辑  收藏  举报

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)