Problem: https://leetcode.com/problems/product-of-array-except-self/
Solution1:
计算第 i 位的左边乘积和右边乘积,再将左右相乘
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] left = new int[nums.length];
int[] right = new int[nums.length];
left[0] = 1;
right[nums.length-1] = 1;
for(int i=1; i<nums.length;i++) {
left[i] = left[i-1] * nums[i-1];
}
for(int j=nums.length-2; j>=0;j--) {
right[j] = right[j+1] * nums[j+1];
}
for(int i=0; i<nums.length;i++) {
nums[i] = left[i] * right[i];
}
return nums;
}
}
时间复杂度:O(n)
空间复杂度:O(n) (因为构造了left和right两个数组)
Solution2:
不再创造新数组存储右边的乘积,而是沿用左边乘积的数组
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] ans = new int[nums.length];
ans[0] = 1;
// 同样的先计算左边乘积
for(int i=1; i<nums.length;i++) {
ans[i] = ans[i-1] * nums[i-1];
}
// 不再创造右边数组,直接对左边乘积数组进行计算
int R = 1;
for(int i=nums.length-1; i>=0; i--) {
ans[i] *= R;
R *= nums[i];
}
return ans;
}
}
时间复杂度:O(n)
空间复杂度:O(1) (没有创造新的数组,ans数组根据题意不作为空间复杂度考虑因素)
本文介绍了解决LeetCode题目“除自身以外数组的乘积”的两种方法。第一种方法通过创建左右乘积数组,分别计算每个元素左侧和右侧的乘积,最后将两者相乘得到结果,时间复杂度为O(n),空间复杂度为O(n)。第二种方法改进了空间复杂度,利用原始数组存储中间结果,避免额外数组的创建,实现了O(1)的空间复杂度。
565

被折叠的 条评论
为什么被折叠?



