Python-陣列-Array_of_product-返回一個數組中除某個數外其餘元素的乘積
阿新 • • 發佈:2021-02-07
輸入一個數組input = [5, 1, 4, 2]
返回一個數組,這個陣列的每一個元素output[i]都是input中除了input[i]的所有數字的乘積
不能使用除法。
樣例輸出:
[8, 40, 10, 20]
Solution1:
遍歷當前陣列,
進行第二層遍歷
比較下標,將內層遍歷時的下標與外層遍歷的下標不相等的元素依次累乘。
inputarray = [5, 1, 4, 2]
def arrayOfProducts(array):
# Write your code here.
output_array = []
current_product = 1
for _ in range(0,len(array)):
for i in range(0,len(array)):
if _ != i:
current_product *= array[i]
output_array.append(current_product)
current_product = 1
return output_array
print(arrayOfProducts(array = inputarray))
Time:O( n 2 n^2 n2)
Space: O(n)