题目
解析
- 用hashmap记下乘积,先从左到右循环,再从右到左循环
# Approach 1 - more elegent
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
for idx in range(1, len(nums)):
res[idx] = res[idx - 1] * nums[idx - 1]
temp = nums[-1]
for idx in range(len(nums) - 2, -1, -1):
res[idx] = res[idx] * temp
temp = temp * nums[idx]
return res
# Approach 2 - just a bit easier to understand
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
temp = nums[0]
for idx in range(1, len(nums)):
res[idx] = temp
temp = temp * nums[idx]
temp = nums[-1]
for idx in range(len(nums) - 2, -1, -1):
res[idx] = res[idx] * temp
temp = temp * nums[idx]
return res
Ref