leetcode - 238. Product of Array Except Self

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 ( 1 ) o(1) o(1)

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

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)