classSolution(object): defproductExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) l,r = [1] * n, [1]* n for i inrange(1,n): l[i] = l[i-1] * nums[i-1] for i inrange(n-2,-1,-1): r[i] = r[i+1] * nums[i+1] res = [] for i inrange(n): res.append(l[i] * r[i]) return res
优化:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defproductExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) l = [1] * n for i inrange(1, n): l[i] = l[i - 1] * nums[i - 1] r = 1 for i inrange(n - 1, -1, -1): l[i] *= r r *= nums[i] return l