首页 > 代码库 > 238. Product of Array Except Self
238. Product of Array Except Self
https://leetcode.com/problems/product-of-array-except-self/#/description
Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Sol:
If you look at the list above with the multiplication you‘ll notice we are repeating multiplications, such as 2 times 3 or 3 times 4 for multiple entries in the new list.
We‘ll want to take a greedy approach and keep track of these results for later re-use at other indices. We‘ll also need to think about what if a number is zero!
In order to find the products of all the integers (except for the integer at that index) we will actually go through our list twice in a greedy fashion.
On the first pass we will get the products of all the integers before each index, and then on the second pass we will go backwards to get the products of all the integers after each index.
Then we just need to multiply all the products before and after each index in order to get the final product answer!
Let‘s see this in action:
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ output = [] product = 1 i = 0 while i < len(nums): output.append(product) product *= nums[i] i += 1 product = 1 i = len(nums) - 1 while i >= 0: output[i] *= product product *= nums[i] i -= 1 return output
See
Product of integers
238. Product of Array Except Self