LC.P238[除自身以外数组的乘积]

方法一:前缀与后缀乘

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n], left = new int[n], right = new int[n];
left[0] = right[n - 1] = 1;
for (int i = 1; i < n; ++i) left[i] = left[i - 1] * nums[i - 1];
for (int i = n - 2; i >= 0; --i) right[i] = right[i + 1] * nums[i + 1];
for (int i = 0; i < n; ++i) ans[i] = left[i] * right[i];
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:空间优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 1, prod = 1; i <= n; ++i) {
ans[i - 1] = prod;
prod *= nums[i - 1];
}
for (int i = n, prod = 1; i >= 1; --i) {
ans[i - 1] *= prod;
prod *= nums[i - 1];
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$