摘要:題目描述題目解析簡(jiǎn)單來(lái)說(shuō)就是對(duì)于數(shù)組中每一項(xiàng),求其他項(xiàng)之積。算一遍全部元素的積再分別除以每一項(xiàng)要仔細(xì)考慮元素為零的情況。沒(méi)有零直接除下去。一個(gè)零零的位置對(duì)應(yīng)值為其他元素之積,其他位置為零。兩個(gè)以上的零全部都是零。
題目描述
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].
題目解析簡(jiǎn)單來(lái)說(shuō)就是對(duì)于數(shù)組中每一項(xiàng),求其他項(xiàng)之積。
解題思路 對(duì)于每一項(xiàng)硬算其他項(xiàng)之積恭喜你,你超時(shí)了。
算一遍全部元素的積再分別除以每一項(xiàng)要仔細(xì)考慮元素為零的情況。
沒(méi)有零直接除下去。
一個(gè)零零的位置對(duì)應(yīng)值為其他元素之積,其他位置為零。
兩個(gè)以上的零全部都是零。
AC代碼class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ try: from functools import reduce finally: pass res = [] zeros = nums.count(0) if zeros == 0: product = reduce(lambda x, y: x * y, nums) res = [product // x for x in nums] elif zeros == 1: now = nums[::] pos = now.index(0) del now[pos] product = reduce(lambda x, y: x * y, now) res = [0 if x != pos else product for x in range(len(nums))] else: res = [0] * len(nums) return res總結(jié)
遇事多思考,輕易不要循環(huán)。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/45506.html
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...
Problem 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 ...
問(wèn)題: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)....
Problem 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 ...
摘要:動(dòng)態(tài)規(guī)劃復(fù)雜度時(shí)間空間思路分析出自身以外數(shù)組乘積的性質(zhì),它實(shí)際上是自己左邊左右數(shù)的乘積,乘上自己右邊所有數(shù)的乘積。所以我們可以用一個(gè)數(shù)組來(lái)表示第個(gè)數(shù)字前面數(shù)的乘積,這樣。同理,我們可以反向遍歷一遍生成另一個(gè)數(shù)組。 Product of Array Except Self Given an array of n integers where n > 1, nums, return an...
閱讀 902·2021-10-13 09:39
閱讀 3784·2021-10-12 10:12
閱讀 1866·2021-08-13 15:07
閱讀 1069·2019-08-29 15:31
閱讀 2940·2019-08-26 13:25
閱讀 1841·2019-08-23 18:38
閱讀 1954·2019-08-23 18:25
閱讀 1907·2019-08-23 17:20