20 Jun 2024
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105-30 <= nums[i] <= 30Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
answer中的元素,为左半部分(前缀)和右半部分(后缀)。其中左半部分,可以通过循环线性逐个算出,而右半部分,可以倒循环的时候逐个算出。那么先正循环一次,把前缀逐个记住;再倒循环一次,把后缀逐个算出,然后和对应的前缀相乘即可得到结果。
时间复杂度已经无法优化,那么只能优化空间复杂度到O(1)。由于answer是不计算到空间复杂度中的,所以要它身上下手
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: answer = [1] * len(nums) prefix_product_list = [1] * len(nums) for i in range(1, len(nums)): prefix_product_list[i] = prefix_product_list[i-1] * nums[i-1] suffix_product = 1 for j in range(len(nums)-1, -1, -1): answer[j] = prefix_product_list[j] * suffix_product suffix_product *= nums[j] return answer
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: answer = [1] * len(nums) for i in range(1, len(nums)): answer[i] = answer[i-1] * nums[i-1] suffix_product = 1 for j in range(len(nums)-1, -1, -1): answer[j] *= suffix_product suffix_product *= nums[j] return answer