鱼儿慢慢游~~

导航

 

原问题描述:  难度: 中等

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]

中文描述:

给定一个n维的整数数组nums,(n>1),  返回一个n维数组output,并且output[i] 的值为 nums数组中除了nums[i] 之外的所有元素的乘积。

如, 给定nums = [1, 2, 3, 4] 返回:[24, 12, 8, 6]

解答:

看到这个问题第一反应就是,首先计算nums 所有元素的乘积 pro,然后遍历nums, 用 pro/nums[i] 作为output[i]的取值。 但是看到题目要求说能不能不用除法,仔细思考,除法的话,还要考虑nums[i] = 0 的情况,会变得比较复杂。

然后参考他人思想, 得到解决方法:

1.  顺序遍历nums 数组,将output[i] 的值设为 i 之前元素的乘积。

2. 逆序遍历nums数组, 将output[i]的值,乘上i之后元素的乘积。

3. 输出output

算法思想很简单,但是不容易想到,之前有个分发糖果的问题,也是通过顺序遍历和逆序遍历相结合实现的。

算法python的实现:

class Solutin(object):
    def productExceptionSelf(self, nums):
        res = 1
        le = len(nums)
        output = []
        for i in nums:
            output.append(res)
            res *= nums[i]
        res = 1
        for i in range(le-1, -1, -1):
            output[i] *= res
            res *= nums[i]
        return output
View Code

 

posted on 2016-05-10 16:26  miss_UU  阅读(136)  评论(0编辑  收藏  举报