DEnjoy

导航

leetcode日记 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].

题目说明:给定一个数组,求一个新数组满足:每一位上的数等于给定数组除开此位之积。

  最先反应过来的想法为求出整个数组的积然后除以每一位即可,不过再一细想,如果数组中有0的存在,那么整个数组的积即为0,那么这样就需要找到0这个位置,然后再算剩下的积,不过又想0元素可以不止一个,不过如果0不止一个的话那么整个数组的结果就均为0,这样便可以解出结果。

  不过题目要求不使用除法,那么应该怎么办呢?

  题目说明需要线性时间来解决,那么就说明很可能只需要遍历一两次即可,如果正向遍历的话,只能得到到达当前位置之前的数的积,并不能知道当前位置之后的数的积。这样一想,只要把正向遍历反过来,就可以得到当前位置之后的数的积,这样再将得到的前后数乘起来,即可得到题目要求答案。

python代码:

    def productExceptSelf(self, nums):
        tem1=[1]
        tem2=[1]
        length=len(nums)
        for i in xrange(1,length):
            tem=tem1[i-1]*nums[i-1]
            tem1.append(tem)
            tem=nums[length-i]*tem2[i-1]
            tem2.append(tem)
        for i in xrange(length):
            tem1[i]=tem1[i]*tem2[-(i+1)]
        return tem1

这个解法使用了额外的空间,而题目中提了个问题说“Could you solve it with constant space complexity?”,那么这个方法可以优化吗?

很明显,反向所得结果并不需要存下来,只需要存下正向结果,然后实时求出对应位置上的反向结果,直接将结果得出即可:

java代码:

    public int[] productExceptSelf(int[] nums) {
        int []result=new int[nums.length];
        result[0]=1;
        for (int i=1;i<nums.length;i++){
            result[i]=result[i-1]*nums[i-1];
        }
        for (int i=nums.length-2,tem=1;i>=0;i--){//这里不需要从最后一位开始,因为最后一位的反向实时结果为1,与正向结果相乘后结果不变,因此不需要改变
            tem*=nums[i+1];
            result[i]*=tem;
        }
        return result;
    }

 

posted on 2016-12-13 20:56  DEnjoy  阅读(128)  评论(0编辑  收藏  举报