leetcode - 238. Product of Array Except Self

给定一个整数数组,返回一个新的数组,新数组中的每个元素是原数组中所有其他元素的乘积。要求算法在O(n)的时间复杂度内完成,且不能使用除法。两种解决方案分别使用了O(n)的空间复杂度和O(1)的空间复杂度。
摘要由CSDN通过智能技术生成

Description

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]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:

2 <= nums.length <= 10^5
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Solution

space o ( n ) o(n) o(n) solution

Use separate dicts to store the prefix product and suffix product, then the result will be pre_prod[i] * suf_prod[i]

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

space o ( 1 ) o(1) o(1) solution

Use returned list as the pre_prod, then directly times the numbers from the end to the start.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Code

space o ( n ) o(n) o(n) solution

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        pre_pro, suf_pro = {}, {}
        mul = 1
        for i in range(len(nums)):
            pre_pro[i] = mul * nums[i]
            mul *= nums[i]
        mul = 1
        for i in range(len(nums) - 1, -1, -1):
            suf_pro[i] = mul * nums[i]
            mul *= nums[i]
        res = []
        for i in range(len(nums)):
            res.append(pre_pro.get(i - 1, 1) * suf_pro.get(i + 1, 1))
        return res

space o ( 1 ) o(1) o(1) solution

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        res = [1] * len(nums)
        pred_prod = 1
        for i in range(1, len(nums)):
            pred_prod *= nums[i - 1]
            res[i] *= pred_prod
        pre_prod = 1
        for i in range(len(nums) - 2, -1, -1):
            pre_prod *= nums[i + 1]
            res[i] *= pre_prod
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值