238.Product of Array Except self
My code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
ans = [1]*length
pre = 1
post = 1
for i in range(length):
ans[i] *= pre
pre *= nums[i]
ans[length - 1 - i] *= post
post *= nums[length - 1 - i]
return ans
Other code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
zeroes = 0
full_product = 1
for idx, i in enumerate(nums):
if i == 0:
zeroes += 1
if zeroes > 1:
return [0] * len(nums)
position = idx
else:
full_product *= i
if zeroes:
result = [0] * len(nums)
result[position] = full_product
else:
result = [full_product//i for i in nums]
return result