码迷,mamicode.com
首页 > 其他好文 > 详细

(medium)LeetCode 238.Product of Array Except Self

时间:2015-08-04 20:44:27      阅读:193      评论:0      收藏: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)

     技术分享

 

(medium)LeetCode 238.Product of Array Except Self

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!