脑洞不一样大之神奇算法系列再现。
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.)
|
|
愣是没看懂什么意思系列= =
评论区看了大神解答,终于看懂了什么意思。假设数组为[2,3,4,5]
,如果我们要计算res[2]
,也就是2*3*5,那么计算可以分为 left 和 right 两部分,left为2*3,right为5,而最终只需要计算left * right即可,
可以列表为
|
|
所以原代码中
|
|
即为计算left部分,2 的 left 是1,3的 left 是第一列 Numbers * left ,4 的 left 是第二列的 Numbers * left,5 的 left 是第三类列的 Numbers * left。
同理计算 right,分别乘的res中,即为所求。
时间复杂度为O(n),而我们把 left 直接存在了res的数组中,免去了单开 O(n) 的空间复杂度,空间复杂度只有right一个O(1)。
再次跪拜脑洞。