Day17-238. Product of Array Except Self

今日题目:238. Product of Array Except Self

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]

思路

My solution

def productExceptSelf(nums):
    n = len(nums)
    fwd = [1]
    bwd = [1]
    ans = []

    for i in range(1,n):
        forward = fwd[i-1]*nums[i-1]
        fwd.append(forward)
    for j in range(1,n):
        backward = bwd[0]*nums[n-j]
        bwd.insert(0,backward)
    for k in range(n):
        mid = fwd[k]*bwd[k]
        ans.append(mid)
    return ans

Result

https://ithelp.ithome.com.tw/upload/images/20211003/20140843ss8xeVCn7L.png

UPGRADE

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        fwd = [1]

        for i in range(1,n):
            forward = fwd[i-1]*nums[i-1]
            fwd.append(forward)
        right = 1
        for j in range(n-1,-1,-1):
            fwd[j] *= right
            right *= nums[j]
        return fwd

https://ithelp.ithome.com.tw/upload/images/20211003/20140843jCULUgBDNq.png


<<:  110/17 - Android 6图片剪裁

>>:  Day 17:上架 Google Play

Day 4. 关於.NET後端(2)

开开始学後端的人多少会听到ASP.NET、.NET Framework、.NET Core,但不清楚...

Day 27 - Click and Drag to Scroll

前言 JS 30 是由加拿大的全端工程师 Wes Bos 免费提供的 JavaScript 简单应用...

在全域宣告的let

//宣告全域变数 var v = 'global' let l = 'global' //建立fun...

Day 4 Ruby 变数与资料型别 Variable and Data Type

写在前面 因为发现昨天在讲基础运算子的时候很多地方需要先知道变数跟资料型别,所以今天赶快来补充一下。...

django新手村2 ------创建models

上一篇提到 主urls->次urls->views->models->vie...