LeetCode:238. Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
给定一个长度为n的整型数组nums,对于某个位置i,输出数组output在该位置上的元素是nums中除了i位置元素之外所有元素的乘积。求最终的output数组。
思路:乘积 = 当前数左边的乘积 * 当前数右边的乘积
以数组 [2,3,4,5]为例,以 left 数组来记录某个位置左边的所有元素乘积,以right 数组来记录某个位置右边的所有元素乘积,那么对于最终的输出结果output,里面的某个位置的元素值为output[i] = left[i] * right[i]。
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
l = len(nums)
res = [0]*l
left = [1]*l
right = [1]*l
leftProduct = 1
rightProduct = 1
for i in range(1,l):
leftProduct *= nums[i-1]
left[i] = leftProduct
for i in range(0,l-1)[::-1]:
rightProduct *= nums[i+1]
right[i] = rightProduct
res[i] = left[i]*right[i]
res[l-1]=left[l-1]
return res
由于对空间复杂度还有要求,所以改进一下,取出left和right两个数组,直接用res数组暂存:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
l = len(nums)
res = [1]*l
leftProduct = 1
rightProduct = 1
for i in range(1,l):
leftProduct *= nums[i-1]
res[i] = leftProduct
for i in range(0,l-1)[::-1]:
rightProduct *= nums[i+1]
res[i] = res[i]*rightProduct
return res
THE END.