【LEETCODE】238-Product of Array Except Self

来源:互联网 发布:阴阳师攻击力数据排行 编辑:程序博客网 时间:2024/05/15 08:11

Given an array of n integers where n > 1,nums, return an array output such thatoutput[i] is equal to the product of all the elements ofnums 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 arraydoes not count as extra space for the purpose of space complexity analysis.)


题意:

给一个数组,具有n个整数,n>1,

返回一个数组,output[i] 为除了nums[i]之外的其他数的乘积


不用除法division,时间复杂度为O(n)

思考怎样做到常数级空间复杂度


参考:

http://www.tuicool.com/articles/IbUvmeJ


思路:

一共两次遍历,

一次遍历nums,生成output[i]的left的累积

一次遍历nums,生成output[i]的right的累积




class Solution(object):    def productExceptSelf(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        output=[1]*len(nums)                left=1                for i in range(len(nums)-1):                    #累积left            left*=nums[i]            output[i+1]*=left                right=1                for i in range(len(nums)-1,0,-1):               #再累积right            right*=nums[i]            output[i-1]*=right                return output



0 0
原创粉丝点击