Product of Array Except Self
Given an array of n integers where n > 1, nums
,
return an array output
such that output[i]
is
equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
给定一个整型数组,返回一个结果数组,要求返回的数组的第i项表示原数组中除第i项外所有项的乘积,不使用除法,O(n)时间。
假定有数组[a1, a2, ..., ax, c, b1, b2, ... by],那么c的位置返回的应该是a1*a2*...*ax * b1*b2*... *by。
一个简单的思路:使用数组ArrayA存储由前往后,每一项存储到该项所有元素的乘积,使用数组ArrayB存储由后往前,每一项存储该项后面所有元素的乘积,最后将两个数组对应项相乘,所得的乘积数组即为结果数组。
代码:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nLen = len(nums)
ans = [0] * nLen
ans[0] = 1
step = range(nLen)
# 从前往后,该论循环结束后,ans数组的每一项存储该项前面所有元素的乘积
for i in step[1:]:
ans[i] = ans[i - 1] * nums[i - 1]
# 由后往前,nums数组的每一项存储该项及后面所有元素的乘积
for j in step[::-1][1:]:
ans[j] = ans[j] * nums[j + 1]
nums[j] = nums[j] * nums[j + 1]
return ans