赞
踩
【题目】
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
【思路】
【python】
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ #nums = [1, 2, 3, 4] ln =len(nums) left,right = [1]*ln,[1]*ln for i in range(1,ln): left[i] = left[i-1]*nums[i-1] #left = [1, 1, 2, 6] right[ln-i-1] = right[ln-i]*nums[ln-i] #right = [24, 12, 4, 1] res = [1]*ln for i in range(ln): res[i] = left[i]*right[i] return res
【结果】
【学习收获】
题目还有进阶选项:常数空间复杂度O(1),也就是所用空间不随n的变化而变化(除了输出数组空间res)
借鉴高手代码:https://sweets.ml/2019/03/03/leetcode-238/
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n =len(nums)
result = [1 for i in range(n)]
result_left = 1
result_right = 1
for i in range(n-1):
result_left *=nums[i]
result[i+1] =result_left
for i in range(n-1,0,-1): #从n-1到1
result_right *=nums[i]
result[i-1] *= result_right
return result
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。