给定长度为 n 的整数数组 nums
,其中 n > 1,返回输出数组 output
,其中 output[i]
等于 nums
中除 nums[i]
之外其余各元素的乘积。
示例:
输入:[1,2,3,4]
输出:[24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
第一种思路:
不能用除法,那只能用乘法统计其他元素的乘积了,
一共扫两趟,
第一趟从左往右走,开一个数组叫left记录除第一个元素外,其他每个元素的所有左边元素的乘积,left[0] = 1
比如对于[1,2,3,4],我们有left = [1,1, 2, 6],
类似的,第二趟从右往左走,开right数组记录所有右边元素的乘积,right[-1] = 1
比如对于[1,2,3,4],我们有right = [24, 12, 4, 1]
最后把left和right对位相乘,就是需要的结果。
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
l = len(nums)
if l == 0:
return nums
left = [1] * l
right = [1] * l
for i in range(l):
if i == 0:
continue
else:
left[i] = left[i - 1] * nums[i - 1]
for i in range(l - 1, -1, -1):
if i == l - 1:
continue
else:
right[i] = right[i + 1] * nums[i + 1]
res = [0] * l
for i in range(l):
res[i] = left[i] * right[i]
return res
下面的写于2019年8月16日20:32:49:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left, right = [1] * len(nums), [1] * len(nums)
for i in range(1, len(nums)):
left[i] = left[i - 1] * nums[i - 1]
for i in range(len(nums) - 2, -1, -1):
right[i] = right[i + 1] * nums[i + 1]
for i in range(len(nums)):
nums[i] = left[i] * right[i]
return nums
第二种思路:
学习自答案,O(1)的空间就可以实现。
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
d=[1]*len(nums)
for i in range(1,len(nums)):
d[i]=d[i-1]*nums[i-1]
p=1
for i in reversed(range(len(nums))):
d[i]=d[i]*p
p=p*nums[i]
return d
下面的写于2019年8月16日20:49:35
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [1] * len(nums)
for i in range(1, len(nums)):
res[i] = res[i - 1] * nums[i - 1]
tmp = 1
for i in range(len(nums) - 1, -1, -1):
res[i] *= tmp
tmp *= nums[i]
return res