Medium
题目几点要求
left → right
#1
value 1 2 3 4
↑
left 1
right
#2
value 1 2 3 4
↑
left 1 1
right
#3
value 1 2 3 4
↑
left 1 1 2
right
#4
value 1 2 3 4
↑
left 1 1 2 6
right
left ← right
#1
value 1 2 3 4
↑
left 1 1 2 6
right 1
#2
value 1 2 3 4
↑
left 1 1 2 6
right 4 1
#3
value 1 2 3 4
↑
left 1 1 2 6
right 12 4 1
#4
value 1 2 3 4
↑
left 1 1 2 6
right 24 12 4 1
--------------------
left * right
result 24 12 8 6
实际我们也不需要两个数组,只需在一个数组上进行操作即可。 综上,尝试写一下代码,AC!
python3
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
result = [1] * len(nums)
for i in range(1, len(nums)):
result[i] = result[i-1] * nums[i-1]
k = 1
for j in range(len(nums)-1, -1, -1):
result[j] *= k
k *= nums[j]
return result