iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

開學之前....系列 第 16

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


上一篇
Day16-205. Isomorphic Strings
下一篇
Day18-13. Roman to Integer
系列文
開學之前....20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言