Re: [閒聊] 每日leetcode

看板Marginalman作者 (caster )時間1年前 (2024/03/15 10:59), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串47/1548 (看更多)
※ 引述《Rushia (みけねこ的鼻屎)》之銘言: : https://leetcode.com/problems/product-of-array-except-self/ : 238. Product of Array Except Self : 給你一個陣列nums,求出一個列表ls,ls[i] = 除了nums[i]以外的所有元素內積。 : 思路: : 1.ls[i] = (0~i-1的積) * (i+1~n-1的積),遍歷一次用一個陣列紀錄左邊的積,在遍歷 : 一次從右到左,過程紀錄右邊的積,並把右邊的積乘上左邊的就好 : -------------------------------------------- : class Solution: : def productExceptSelf(self, nums: List[int]) -> List[int]: : n = len(nums) : res = [1] * n : res[0] = 1 : for i in range(1, n): : res[i] = res[i - 1] * nums[i - 1] : right = 1 : for i in range(n - 1, -1, -1): : res[i] *= right : right *= nums[i] : return res : -------------------------------------------- 以前寫過 思路差不多 不過我的空間時間都在倒數20% 參考溫莎寫法修改後能贏70%的人 Python code: class Solution def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) l = [] r = [] res = [] a = 1 for i in range(n-1): a *= nums[i] l.append(a) b = 1 for i in range(n-1,0,-1): b *=nums[i] r.append(b) for i in range(n): if i == 0: res.append(r[-1]) elif i == n-1: res.append(l[-1]) else: res.append(l[i-1]*r[-i-1]) return res -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.139.10 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1710471583.A.8DD.html

03/15 11:07, 1年前 , 1F
大師別卷了
03/15 11:07, 1F

03/15 11:16, 1年前 , 2F
大師
03/15 11:16, 2F
文章代碼(AID): #1byxcVZT (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1byxcVZT (Marginalman)