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.)
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.)
Solution1: run time complexity is O(n), space complexity is O(n).
res = [n2*n3*n4, n1*n3*n4, n1*n2*n4, n1*n2*n3], 相当于a1 = [1, n1, n1*n2, n1*n2*n3]和
a2 = [n2*n3*n4, n3*n4, n4, 1]相乘
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
int[] a1 = new int[nums.length];
int[] a2 = new int[nums.length];
a1[0] = 1;
a2[nums.length - 1] = 1;
// scan from left to right -> a1 = [1, n1, n1*n2, n1*n2*n3]
for (int i = 0; i < nums.length - 1; i++) {
a1[i + 1] = nums[i] * a1[i];
}
// scan from right to left -> a2 = [n2*n3*n4, n3*n4, n4, 1]
for (int i = nums.length - 1; i > 0; i--) {
a2[i - 1] = nums[i] * a2[i];
}
// multiply -> res = [n2*n3*n4, n1*n3*n4, n1*n2*n4, n1*n2*n3]
for (int i = 0; i < nums.length; i++) {
res[i] = a1[i] * a2[i];
}
return res;
}
}
Solution2: run time complexity is O(n), constant space.
用一个temp来保存每次的结果。public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
res[0] = 1;
int temp = 1;
for (int i = 1; i < nums.length; i++) {
temp = temp * nums[i - 1];
res[i] = temp;
}
temp = 1;
for (int i = nums.length - 2; i >= 0; i--) {
temp = temp * nums[i + 1];
res[i] *= temp;
}
return res;
}
}
No comments:
Post a Comment