Product of Array Except Self

脑洞不一样大之神奇算法系列再现。

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
5
6
7
8
9
10
11
12
13
14
15
public 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;
}

愣是没看懂什么意思系列= =

评论区看了大神解答,终于看懂了什么意思。假设数组为[2,3,4,5],如果我们要计算res[2],也就是2*3*5,那么计算可以分为 left 和 right 两部分,left为2*3,right为5,而最终只需要计算left * right即可,

可以列表为

1
2
3
Numbers 2 3 4 5
left 1 2 2*3 2*3*4
right 3*4*5 4*5 5 1

所以原代码中

1
res[i] = res[i - 1] * nums[i - 1]

即为计算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)。

再次跪拜脑洞。