238 Product of Array Except Self
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.)
思路
题目要我们求出数组除了当前元素以外的所有数的乘积,不能使用除法,并使用O(n)的时间复杂度。经过一番……很长时间的考虑,也没想出来。
实际上是一个典型的空间换时间的方法,从左往右记录该元素以左(不含该元素)的累乘结果;再从右向左做一次。最后的结果是两组结果对应的乘积。
|
|