Leetcode - 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.)

[分析]
基本思路:数组中第 i 个元素除自身外的数组乘积=product(1,i-1) * product(i + 1, N -1),
因此开辟两个数组prior 和 after,prior[i]=product(1,i-1), after[i]=product(i + 1, N -1)。
优化思路:在基本思路基础上如何优化空间效率呢,能否只使用常数的额外空间?注意到prior[i]=prior[i-1]*nums[i-1],且我们只需要当前的prior[i],因此只使用一个变量即可,每次迭代时更新即可,而原来的after[]就可以直接存放在结果数组中,结果从前往后计算,计算到i位置时,i前面的都是最终结果,i后面的则是基本思路中after[]数组内容。


public class Solution {
// base version
public int[] productExceptSelf1(int[] nums) {
if (nums == null) return null;
int N = nums.length;
int[] ret = new int[N];
int[] prior = new int[N];
int[] after = new int[N];
prior[0] = 1;
for (int i = 1; i < N; i++) {
prior[i] = prior[i - 1] * nums[i - 1];
}
after[N - 1] = 1;
for (int i = N - 2; i >= 0; i--) {
after[i] = after[i + 1] * nums[i + 1];
}
for (int i = 0; i < N; i++) {
ret[i] = prior[i] * after[i];
}
return ret;
}
// optimized version
public int[] productExceptSelf(int[] nums) {
if (nums == null) return null;
int N = nums.length;
int[] ret = new int[N];
ret[N - 1] = 1;
for (int i = N - 2; i >= 0; i--) {
ret[i] = ret[i + 1] * nums[i + 1];
}
int prior = 1;
for (int i = 0; i < N; i++) {
ret[i] = prior * ret[i];
prior *= nums[i];
}
return ret;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值