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[]数组内容。
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;
}
}
212

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



