基本思路,除了选中的值不乘,可以考虑维护左右两个数组,分别代表左侧和右侧的乘积,最后只需要左右相乘,就是除了选中值的乘积,代码如下:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
L,R,ans=[1]*len(nums),[1]*len(nums),[]
L[0]=1
R[len(nums)-1]=1
for i in range (1,len(nums)):
L[i]=nums[i-1]* L[i - 1]
for j in range (len(nums)-2,-1,-1):
R[j]=nums[j+1]* R[j + 1]
for i in range (len(nums)):
ans.append(L[i]*R[i])
return ans