ZhongKuo0228 / study

0 stars 0 forks source link

238. Product of Array Except Self #65

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago
  1. 用 prev_prod 作為第 i 個數字前的乘積
  2. 從後面起算,並用 cur_prod 帶出後面累積的乘積給前面
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        prev_prod = [1 for _ in range(len(nums))]
        results = [1 for _ in range(len(nums))]
        curr_prod = 1
        for i in range(1, len(nums)):
            prev_prod[i] = prev_prod[i - 1] * nums[i - 1]
        for i in range(len(nums) - 1, -1, -1):
            results[i] = prev_prod[i] * curr_prod
            curr_prod *= nums[i]
        return results
fockspaces commented 1 year ago

GPT improve:

  1. prev_prod 可以拿掉,直接用 results 來記錄
  2. list 宣告可以用 [1] * length
  3. 要倒著算,可以用 reversed(range(length)) 取代 range(length - 1, -1, -1)
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        results = [1] * len(nums)
        right_prod = 1
        for i in range(1, len(nums)):
            results[i] = results[i - 1] * nums[i - 1]
        for i in reversed(range(len(nums))):
            results[i] *= right_prod
            right_prod *= nums[i]
        return results