238.除自身以外数组的乘积

思路:某一位置的结果等于该位置的前缀和乘该位置的后缀和,往前遍历一遍记录前缀和,往后遍历一遍记录后缀和

class Solution(object):
    def productExceptSelf(self, nums):
        n = len(nums)
        res = [0]*n
        res[0] = 1
        for i in range(1,n):
            res[i] = res[i-1]*nums[i-1]
        right = nums[-1]
        for j in range(n-1,0,-1):
            res[j-1] *= right
            right *= nums[j-1]
        return res

你可能感兴趣的:(238.除自身以外数组的乘积)