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

LeetCode-Product of Array Except Self

时间:2015-07-31 10:33:59      阅读:144      评论: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数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:

Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]
要求不用除法,时间复杂度O(n)

解题思路基于以下集合

{              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
{ a[1]*a[2]*a[3],    a[2]*a[3],         a[3],                 1,  }
很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?

空间复杂度为O(n)的实现:

public int[] productExceptSelf(int[] nums) {
        int[] productBelow = new int[nums.length];
        int n = 1;
        for (int i = 0; i < nums.length; i++) {
        	productBelow[i] = n;
        	n *= nums[i];
        }
        
        int[] productAbove = new int[nums.length];
        n = 1;
        for (int i = nums.length-1; i >= 0; i--) {
        	productAbove[i] = n;
        	n *= nums[i];
        }
        
        int[] output = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
        	output[i] = productAbove[i] * productBelow[i];
        }
        return output;
    }
但是,如果要求是O(1)的空间复杂度呢?只需要把最后两步合二为一即可:
int[] output = new int[nums.length];
        int n = 1;
        for (int i = 0; i < nums.length; i++) {
        	output[i] = n;
        	n *= nums[i];
        }
        
        n = 1;
        for (int i = nums.length-1; i >= 0; i--) {
        	output[i] *= n;
        	n *= nums[i];
        }
        return output;


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode-Product of Array Except Self

标签:

原文地址:http://blog.csdn.net/my_jobs/article/details/47165619

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