题目描述
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
1 | Input: [1,2,3,4] |
Note: Please solve it without division and in O(n).
这题要求不使用除法,在O(n)内完成。
实际上,对于index为i来说这个乘法操作可以看成是对0到i-1的数字的累乘结果乘上i+1到n的累乘结果。这里的累乘结果可以存在另外两个vector中,在最终的输出中,只需要查找两个数组,把合适位置的值乘起来就可以了。需要遍历三次数组即可。
代码实现
1 | class Solution { |