您的位置:首页 > 其它

Product of Array Except Self

2015-08-26 19:24 393 查看
题目:

Given an array of n integers where n > 1,
nums
,
return an array
output
such that
output[i]
is
equal to the product of all the elements of
nums
except
nums[i]
.

Solve it without division and in O(n).

For example, given
[1,2,3,4]
, return
[24,12,8,6]
.

Follow up:

Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
解题思路:

思路1(不合题目限制,但是AC):

考虑三种情况:(1)当所有元素均为非0数时... (2)当有一个元素为0时... (2)当有多于一个元素为0时...

class Solution(object):

def productExceptSelf(self, nums):

"""

:type nums: List[int]

:rtype: List[int]

"""

ans = []

sum_all, numOfzero = 1,0

for v in nums:

if v!=0:

sum_all *= v

else:

numOfzero += 1

if numOfzero>1:

return [0 for i in range(len(nums))]

elif numOfzero==1:

for v in nums:

if v!=0:

ans.append(0)

else:

ans.append(sum_all)

else:

for v in nums:

ans.append(sum_all/v)

return ans

思路二:

我们可以申请一个等大的数组,第一个记录对应第一个元素的前面数字乘积,很显然是1(因为当前数字不算,而之前又没有数字,只能是1);往后递推,第二个记录对应除第二个元素之前的所有数字乘积,即需要刚才的1乘以刚才的第一个数字;形成数组left。从左往右遍历完成之后,left中对应数字的结果是所有左侧数字的乘积;那再从右往左便利一遍,再记录对应数字右侧所有数字的乘积,形成right。最终把两个数乘起来,不就得到想要的结果了吗。

另外,从右往左乘的过程,其实没有必要再申请一个新的数组了,只需要申请个别变量记录当前值,在刚才的数组上做即可。因为,当前值只跟上一个值有关。

通过一左一右两次扫描,就能够得到所求结果了。

class Solution(object):

def productExceptSelf(self, nums):

"""

:type nums: List[int]

:rtype: List[int]

"""

res = [0 for i in nums]

for i,v in enumerate(nums):

if i==0:

res[i] = 1

continue

res[i] = res[i-1]*nums[i-1]

j = len(res)-2

n = nums[j+1]

while j>=0:

res[j] = res[j]*n

j = j-1

n = n*nums[j+1]

return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: