Product of Array Except Self

数组除了自己剩余数的乘积

题目

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
//计算左边乘积
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;//将右边乘积合并到左边
right *= nums[i];//计算右边乘积
}
return res;
}
}
undefined