- LeetCode 238. Product of Array E
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
这一题的思路是,首先扫描一遍数组,在这里需要完成两件事,第一件事计算乘积,第二件事计算0的个数,如果当前的位置上数字不为零,需要做乘法,如果当前位置上数字为零,不做乘法,count+1, 如果此时count为2,说明有两个零,对于数组来说有两个零,最后的输出就都是0,此时可以直接跳出来循环了。代码如下:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums) < 2:
return []
res = [0 for i in range(len(nums))]
count = 0
product = 1
for i in range(len(nums)):
if nums[i] == 0:
count += 1
index = i
if count == 2:
break
else:
product *= nums[i]
if count == 0:
for i in range(len(nums)):
res[i] = product / nums[i]
elif count == 1:
res[index] = product
return res
网友评论