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.)
题意:给定一个数组,返回一个结果数组。要求结果数组中的每个元素,等于原数组中的该位置以外的元素的乘积。
例如{1,2,3,4},1位置上的,为2*3*4,那么结果数组的0位就是24
要求不能使用除法,并且时间复杂度为O(n)
你能在常数空间实现吗?output[]数组的空间不计算在内
分类:数组
解法1:解法有点巧妙。使用一个数组,保存元素组某位置,例如i,保存i前的所以元素的乘积
另外一个数组,保存i后所有元素的乘积
最后这两个数组相乘
优化一下代码:
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47906303