Posted on 2024-03-15 17:55
Uriel 閱讀(28)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code
給出一個數組nums,輸出同樣長度的數組,每個元素值為該數組所有數字的乘積除以nums[i],要求不用除法
先從左到右掃一遍算prefix product,再從后向左掃一遍算suffix product
1 #576
2 #Runtime: 177 ms (Beats 26.93%)
3 #Memory: 17.4 MB (Beats 96.45%)
4
5 class Solution(object):
6 def productExceptSelf(self, nums):
7 """
8 :type nums: List[int]
9 :rtype: List[int]
10 """
11 t = 1
12 ans = []
13 for i in xrange(len(nums)):
14 ans.append(t)
15 t *= nums[i]
16 t = 1
17 for i in xrange(len(nums) - 1, -1, -1):
18 ans[i] *= t
19 t *= nums[i]
20 return ans
21