跳至主要內容

Leetcode 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]

Example 2:

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

By calculating prefix and postfix, we can get a way like this

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        prefix = []
        postfix = []

        result = []

        for n in nums:
            if len(prefix) is 0:
                prefix.append(n)
            else:
                last_element = prefix[len(prefix) - 1]
                prefix.append(n * last_element)

        for n in reversed(nums):
            if len(postfix) is 0:
                postfix.insert(0, n)
            else:
                last_element = postfix[0]
                postfix.insert(0, n * last_element)

        for index in range(0, len(nums)):
            if index == 0:
                prefix_num = 1
            else:
                prefix_num = prefix[index - 1]

            if index == len(nums) - 1:
                postfix_num = 1
            else:
                postfix_num = postfix[index + 1]
            
            result.append(prefix_num * postfix_num)
        
        return result

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.)

We can combine prefix and postfix array into result array instead of using 2 different arrays

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        result = []

        for n in nums[:-1]:
            if len(result) is 0:
                result.append(1)
                result.append(n)
            else:
                prefix_num = result[len(result) - 1]
                result.append(n * prefix_num)

        postfix = 1

        for index in range(len(nums) -1, 0, -1):
            postfix = nums[index] * postfix

            result[index - 1] = result[index - 1] * postfix

        return result
分類:ArrayLeetcode

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題