数组除了自己剩余数的乘积
题目
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:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
解析重点
1.一开始我想着计算数组所有数的乘积,然后一个循环除以每个数自身即可,但是这里不让用除法。
2.那么我们怎么得到结果呢?a[i]=a[1]…a[i-1]a[i+1]*…a[n],根据上式,我们可以以a[i]为界限,把计算分为两部分,左边和右边乘积。这样我们只需要把数组
循环两次,第一次计算左边的乘积,第二次计算右边的乘积,合起来即为结果。
java代码
1 | class Solution { |