[Topic] Prefix Sum

Posted by 西维蜀黍的OJ Blog on 2023-10-26, Last Modified on 2024-02-01

题目

解析

238. Product of Array Except Self

  • 用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