作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Fri Mar 15 10:08:58 2024
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
--------------------------------------------
--
https://i.imgur.com/bFRiqA3.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.161.152 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1710468541.A.DE8.html
推 JIWP: 大師 03/15 10:27
推 digua: 大師 03/15 10:28
推 DJYOSHITAKA: 大濕 03/15 10:32
→ NCKUEECS: 大師 03/16 01:43