Description:
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.)
算法分析:
這道題給定我們一個數組,讓我們返回一個新數組,對於每一個位置上的數是其他位置上數的乘積,並且限定了時間複雜度O(n),並且不讓我們用除法。如果讓用除法的話,那這道題就應該屬於Easy,因爲可以先遍歷一遍數組求出所有數字之積,然後除以對應位置的上的數字。但是這道題禁止我們使用除法,那麼我們只能另闢蹊徑。我們可以先遍歷一遍數組,每一個位置上存之前所有數字的乘積。那麼一遍下來,最後一個位置上的數字是之前所有數字之積,是符合題目要求的,只是前面所有的數還需要在繼續乘。我們這時候再從後往前掃描,每個位置上的數在乘以後面所有數字之積,對於最後一個位置來說,由於後面沒有數字了,所以乘以1就行。
代碼如下:
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res =[1 for i in nums]
length = len(nums)
res[1] =1
for i in range(1,length):
res[i] = res[i-1]*nums[i]
right =1
for j in range(length):
res[length-1-j] = res[length-1-j]*right
right = right*nums[j]
return res